const { query } = require("./connection");

/**
 * Get rental with all related details (owner, renter, item).
 * @param {string} rentalId - UUID of the rental
 * @returns {Promise<object|null>} Rental with relations or null if not found
 */
async function getRentalWithDetails(rentalId) {
  const result = await query(
    `SELECT
      r.id,
      r."itemId",
      r."renterId",
      r."ownerId",
      r."startDateTime",
      r."endDateTime",
      r."totalAmount",
      r.status,
      r."createdAt",
      r."updatedAt",
      -- Owner fields
      owner.id AS "owner_id",
      owner.email AS "owner_email",
      owner."firstName" AS "owner_firstName",
      owner."lastName" AS "owner_lastName",
      -- Renter fields
      renter.id AS "renter_id",
      renter.email AS "renter_email",
      renter."firstName" AS "renter_firstName",
      renter."lastName" AS "renter_lastName",
      -- Item fields
      item.id AS "item_id",
      item.name AS "item_name",
      item.description AS "item_description"
    FROM "Rentals" r
    INNER JOIN "Users" owner ON r."ownerId" = owner.id
    INNER JOIN "Users" renter ON r."renterId" = renter.id
    INNER JOIN "Items" item ON r."itemId" = item.id
    WHERE r.id = $1`,
    [rentalId]
  );

  if (result.rows.length === 0) {
    return null;
  }

  const row = result.rows[0];

  // Transform flat result into nested structure
  return {
    id: row.id,
    itemId: row.itemId,
    renterId: row.renterId,
    ownerId: row.ownerId,
    startDateTime: row.startDateTime,
    endDateTime: row.endDateTime,
    totalAmount: row.totalAmount,
    status: row.status,
    createdAt: row.createdAt,
    updatedAt: row.updatedAt,
    owner: {
      id: row.owner_id,
      email: row.owner_email,
      firstName: row.owner_firstName,
      lastName: row.owner_lastName,
    },
    renter: {
      id: row.renter_id,
      email: row.renter_email,
      firstName: row.renter_firstName,
      lastName: row.renter_lastName,
    },
    item: {
      id: row.item_id,
      name: row.item_name,
      description: row.item_description,
    },
  };
}

/**
 * Get user by ID.
 * @param {string} userId - UUID of the user
 * @returns {Promise<object|null>} User or null if not found
 */
async function getUserById(userId) {
  const result = await query(
    `SELECT
      id,
      email,
      "firstName",
      "lastName",
      phone
    FROM "Users"
    WHERE id = $1`,
    [userId]
  );

  if (result.rows.length === 0) {
    return null;
  }

  return result.rows[0];
}

module.exports = {
  getRentalWithDetails,
  getUserById,
};
