import { Request, Response } from 'express';
import { z } from 'zod';
import { db } from '../../lib/prisma';
import { AppError, BadRequestError } from '../../lib/errors';
import { createRoom } from './rooms.service';

/**
 * Rooms from a sheet (Sprint 1, TEPL): one row per room, with its block
 * (a property, by name), floor, number, bed count and type. Rooms that already
 * exist are left as they are and reported, so a sheet can be sent again
 * after fixing the rows that failed.
 */
export const importRoomsSchema = z.object({
  rows: z
    .array(
      z.object({
        block: z.string().trim().max(120).optional().nullable(),
        floor: z.number().int().min(0).max(200),
        room: z.string().trim().min(1).max(20),
        beds: z.number().int().min(1).max(50),
        type: z.string().trim().max(40).optional().nullable(),
      }),
    )
    .min(1, 'The sheet has no rows')
    .max(1000, 'Import at most 1000 rooms at a time'),
});

type Row = z.infer<typeof importRoomsSchema>['rows'][number];

export async function importRooms(rows: Row[], propertyIdIn?: string) {
  const properties = await db.property.findMany({ select: { id: true, name: true }, orderBy: { createdAt: 'asc' } });
  if (properties.length === 0) throw new BadRequestError('Add a property first.');
  const fallback = properties.find((p) => p.id === propertyIdIn) ?? properties[0];
  const results: { row: number; status: 'created' | 'exists' | 'error'; message?: string; block: string; room: string }[] = [];
  let beds = 0;
  for (const [i, r] of rows.entries()) {
    const row = i + 2;
    const property = r.block ? properties.find((p) => p.name.toLowerCase() === r.block!.toLowerCase()) : fallback;
    try {
      if (!property) throw new BadRequestError(`No property called “${r.block}” — add it under Properties first`);
      const existing = await db.room.findFirst({ where: { propertyId: property.id, archivedAt: null, number: { equals: r.room, mode: 'insensitive' } }, select: { id: true } });
      if (existing) {
        results.push({ row, status: 'exists', block: property.name, room: r.room });
        continue;
      }
      await createRoom({ propertyId: property.id, number: r.room, floor: r.floor, bedCount: r.beds, bedNaming: 'NUMBERS', ...(r.type ? { type: r.type } : {}) });
      beds += r.beds;
      results.push({ row, status: 'created', block: property.name, room: r.room });
    } catch (e) {
      results.push({ row, status: 'error', message: e instanceof AppError ? e.message : 'Could not import this room', block: property?.name ?? r.block ?? '', room: r.room });
    }
  }
  return {
    created: results.filter((x) => x.status === 'created').length,
    existing: results.filter((x) => x.status === 'exists').length,
    failed: results.filter((x) => x.status === 'error').length,
    beds,
    results,
  };
}

export async function importRoomsHandler(req: Request, res: Response): Promise<void> {
  const { rows } = importRoomsSchema.parse(req.body ?? {});
  res.json(await importRooms(rows, req.propertyId));
}
