import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { BedStatus } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { requirePermission } from '../../middleware/requirePermission';
import { db, prismaUnscoped } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { ConflictError, NotFoundError } from '../../lib/errors';
import { assertWithinPlanLimit } from '../plans/plan-limits';
import { propertyDetailsSchema } from './property.schemas';
import { getSearch } from '../../lib/pagination';

const createSchema = propertyDetailsSchema.extend({
  name: z.string().min(2).max(120),
});
const updateSchema = createSchema.partial().extend({ isArchived: z.boolean().optional() });

export const propertyRouter = Router();
propertyRouter.use(authenticate, requirePermission('MANAGE_ROOMS'));

/**
 * List the tenant's properties, creating a default one on first access so
 * single-property tenants never see an empty state.
 */
/** Counts for the properties stat cards, via COUNT rather than loaded rows. */
propertyRouter.get(
  '/stats',
  asyncHandler(async (_req: Request, res: Response) => {
    const [properties, rooms, students] = await Promise.all([
      db.property.count(),
      db.room.count({ where: { archivedAt: null, floor: { not: null } } }),
      db.studentProfile.count(),
    ]);
    res.json({ stats: { properties, rooms, students } });
  }),
);

propertyRouter.get(
  '/',
  asyncHandler(async (req: Request, res: Response) => {
    // Not paginated: the property switcher needs every property by definition,
    // and the plan caps how many a tenant can have.
    const q = getSearch(req.query);
    const where = q
      ? {
          OR: [
            { name: { contains: q, mode: 'insensitive' as const } },
            { city: { contains: q, mode: 'insensitive' as const } },
          ],
        }
      : {};

    // A tenant with no property gets one created on first read. Only seed when
    // nothing is filtered out, or an unmatched search would create a property.
    if (!q && (await db.property.count()) === 0) {
      await db.property.create({ data: { name: 'Main Property', tenantId: req.user!.tenantId! } });
    }

    const properties = await db.property.findMany({
      where,
      include: { _count: { select: { rooms: { where: { archivedAt: null, floor: { not: null } } }, studentProfiles: true } } },
      orderBy: { createdAt: 'asc' },
    });
    res.json({
      properties: properties.map(({ _count, ...p }) => ({
        ...p,
        roomCount: _count.rooms,
        studentCount: _count.studentProfiles,
      })),
    });
  }),
);

/** Back-compat: the single "current" property (first one). */
propertyRouter.get(
  '/current',
  asyncHandler(async (req: Request, res: Response) => {
    let property = await db.property.findFirst({ orderBy: { createdAt: 'asc' } });
    if (!property) {
      property = await db.property.create({ data: { name: 'Main Property', tenantId: req.user!.tenantId! } });
    }
    res.json({ property });
  }),
);

/**
 * One property with its occupancy broken down.
 *
 * Beds hang off rooms, not the property, so these are counted with a groupBy
 * rather than a `_count` — and only for the property being opened, so the list
 * endpoint does not pay for it on every load.
 */
propertyRouter.get(
  '/:id',
  asyncHandler(async (req: Request, res: Response) => {
    const property = await db.property.findFirst({
      where: { id: req.params.id },
      include: { _count: { select: { rooms: { where: { archivedAt: null, floor: { not: null } } }, studentProfiles: true } } },
    });
    if (!property) throw new NotFoundError('Property not found');

    const beds = await db.bed.groupBy({
      by: ['status'],
      where: { archivedAt: null, room: { propertyId: property.id, floor: { not: null } } },
      _count: { _all: true },
    });
    const byStatus = (status: BedStatus) => beds.find((b) => b.status === status)?._count._all ?? 0;

    const { _count, ...rest } = property;
    res.json({
      property: {
        ...rest,
        roomCount: _count.rooms,
        studentCount: _count.studentProfiles,
        bedCount: beds.reduce((n, b) => n + b._count._all, 0),
        occupiedBeds: byStatus(BedStatus.OCCUPIED),
        vacantBeds: byStatus(BedStatus.VACANT),
        reservedBeds: byStatus(BedStatus.RESERVED),
      },
    });
  }),
);

propertyRouter.post(
  '/',
  asyncHandler(async (req: Request, res: Response) => {
    const input = createSchema.parse(req.body);
    const tenantId = getTenantIdOrThrow();

    await assertWithinPlanLimit('properties');

    const property = await db.property.create({ data: { ...input, tenantId } });
    res.status(201).json({ property });
  }),
);

propertyRouter.patch(
  '/:id',
  asyncHandler(async (req: Request, res: Response) => {
    const input = updateSchema.parse(req.body);
    const existing = await db.property.findFirst({ where: { id: req.params.id } });
    if (!existing) throw new NotFoundError('Property not found');
    if (input.publicSlug) {
      const taken = await prismaUnscoped.property.findUnique({ where: { publicSlug: input.publicSlug }, select: { id: true } });
      if (taken && taken.id !== existing.id) throw new ConflictError('That web address is already taken — pick another');
    }
    const property = await db.property.update({ where: { id: req.params.id }, data: input });
    res.json({ property });
  }),
);

propertyRouter.delete(
  '/:id',
  asyncHandler(async (req: Request, res: Response) => {
    const property = await db.property.findFirst({
      where: { id: req.params.id },
      include: { _count: { select: { rooms: { where: { archivedAt: null } }, studentProfiles: true } } },
    });
    if (!property) throw new NotFoundError('Property not found');
    if (property._count.rooms > 0 || property._count.studentProfiles > 0) {
      throw new ConflictError('Move or remove this property’s rooms and students before deleting it');
    }
    const total = await db.property.count({});
    if (total <= 1) throw new ConflictError('A hostel must have at least one property');
    await db.property.delete({ where: { id: req.params.id } });
    res.status(204).send();
  }),
);
