import { Request, Response } from 'express';
import { createRoomSchema, updateRoomSchema, addBedSchema, renameBedSchema, updateBedStatusSchema, setBedRentSchema } from './rooms.schemas';
import * as svc from './rooms.service';
import { z } from 'zod';
import { getPagination, getSearch } from '../../lib/pagination';

export async function createRoom(req: Request, res: Response): Promise<void> {
  const input = createRoomSchema.parse(req.body);
  res.status(201).json({ room: await svc.createRoom(input) });
}

export async function roomStats(req: Request, res: Response): Promise<void> {
  const propertyId = typeof req.query.propertyId === 'string' ? req.query.propertyId : req.propertyId;
  // `setup=true` (Sprint L4) adds what the getting-started steps need, so they need not read every room.
  if (req.query.setup === 'true') {
    const [stats, setup] = await Promise.all([svc.roomStats(propertyId), svc.setupCounts(propertyId)]);
    res.json({ stats, setup });
    return;
  }
  res.json({ stats: await svc.roomStats(propertyId) });
}

/** Sprint L4: beds to pick from, a page at a time, in the active property (X-Property-Id). */
export async function bedChoices(req: Request, res: Response): Promise<void> {
  const pagination = getPagination(req.query) ?? { page: 1, limit: 25, skip: 0 };
  const status = z.enum(['VACANT', 'ANY']).default('VACANT').parse(req.query.status || undefined);
  const id = z.string().uuid().optional().parse(req.query.id || undefined);
  res.json(await svc.bedChoices(req.propertyId, { q: getSearch(req.query), any: status === 'ANY', id }, pagination));
}

export async function listRooms(req: Request, res: Response): Promise<void> {
  // Explicit ?propertyId wins; otherwise fall back to the active property.
  const propertyId = typeof req.query.propertyId === 'string' ? req.query.propertyId : req.propertyId;
  const pagination = getPagination(req.query);
  const result = await svc.listRooms(propertyId, getSearch(req.query), { floor: floorOf(req.query.floor), pagination });
  res.json(pagination ? result : { rooms: result });
}

/** `?floor=3`, or `?floor=none` for rooms with no floor. Absent means every floor, as before. */
function floorOf(raw: unknown): number | null | undefined {
  if (raw === undefined) return undefined;
  if (raw === 'none') return null;
  return z.coerce.number().int().min(-5).max(500).parse(raw);
}

export async function roomFloors(req: Request, res: Response): Promise<void> {
  const propertyId = typeof req.query.propertyId === 'string' ? req.query.propertyId : req.propertyId;
  res.json(await svc.roomFloors(propertyId));
}

export async function roomSummary(req: Request, res: Response): Promise<void> {
  const propertyId = typeof req.query.propertyId === 'string' ? req.query.propertyId : req.propertyId;
  res.json({ summary: await svc.roomSummary(propertyId) });
}

export async function updateRoom(req: Request, res: Response): Promise<void> {
  const data = updateRoomSchema.parse(req.body);
  res.json({ room: await svc.updateRoom(req.params.id, data) });
}

export async function deleteRoom(req: Request, res: Response): Promise<void> {
  // Deleted, or archived when it has booking history: a 204 either way.
  await svc.deleteRoom(req.params.id);
  res.status(204).send();
}

export async function addBed(req: Request, res: Response): Promise<void> {
  const { roomId, label, count, extra } = addBedSchema.parse(req.body);
  const beds = await svc.addBeds(roomId, { label, count, extra });
  // `bed` as before (the first one); `beds` for clients that add several.
  res.status(201).json({ bed: beds[0], beds });
}

export async function updateBedStatus(req: Request, res: Response): Promise<void> {
  const { status } = updateBedStatusSchema.parse(req.body);
  res.json({ bed: await svc.updateBedStatus(req.params.id, status) });
}

export async function renameBed(req: Request, res: Response): Promise<void> {
  const { label } = renameBedSchema.parse(req.body);
  res.json({ bed: await svc.renameBed(req.params.id, label) });
}

export async function deleteBed(req: Request, res: Response): Promise<void> {
  await svc.deleteBed(req.params.id);
  res.status(204).send();
}

export async function setBedRent(req: Request, res: Response): Promise<void> {
  const { monthlyRent, rentDueDay, nightlyRent } = setBedRentSchema.parse(req.body);
  res.json({ bed: await svc.setBedRent(req.params.id, monthlyRent, rentDueDay, nightlyRent) });
}
