import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { Role } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { authorize } from '../../middleware/authorize';
import { prismaUnscoped } from '../../lib/prisma';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { planShortfall, tenantUsage } from './plan-limits';

/**
 * Subscription plans are PLATFORM-level (not tenant data), so every query here
 * intentionally uses the UNSCOPED client and the routes are SUPER_ADMIN-only.
 */
// A plan is sized by properties and beds. Blank (null) is unlimited; a figure
// is a whole number of at least one. The old maxRooms / maxStudents fields are
// no longer accepted — a body that still sends them has them dropped.
const limit = (what: string) =>
  z.coerce
    .number({ invalid_type_error: `Max ${what} must be a number` })
    .int(`Max ${what} must be a whole number`)
    .min(1, `Max ${what} must be at least 1, or left blank for unlimited`)
    .max(100_000, `Max ${what} cannot be more than 100,000`)
    .nullable()
    .optional();
const base = z.object({
  name: z.string().trim().min(2, 'Plan name must be at least 2 characters').max(60, 'Plan name must be at most 60 characters'),
  monthlyPrice: z.coerce.number().int('Price must be whole rupees').min(0, 'Price cannot be negative').max(10_000_000).default(0),
  maxProperties: limit('properties'),
  maxBeds: limit('beds'),
  features: z.array(z.string().trim().min(1).max(80)).max(20, 'At most 20 features').default([]),
  isDefault: z.boolean().optional(),
});
/** Every property needs at least one bed, so a plan cannot offer more properties than beds. */
function bedsCoverProperties(maxProperties: number | null | undefined, maxBeds: number | null | undefined) {
  if (maxProperties != null && maxBeds != null && maxBeds < maxProperties) {
    throw new BadRequestError(`Max beds (${maxBeds}) cannot be less than max properties (${maxProperties}): every property needs at least one bed`);
  }
}
const createSchema = base;
const updateSchema = base.partial().extend({ isActive: z.boolean().optional() });

export const planRouter = Router();
planRouter.use(authenticate, authorize(Role.SUPER_ADMIN));

planRouter.get(
  '/',
  asyncHandler(async (_req: Request, res: Response) => {
    const plans = await prismaUnscoped.plan.findMany({
      include: { _count: { select: { tenants: true } } },
      orderBy: [{ monthlyPrice: 'asc' }, { createdAt: 'asc' }],
    });
    res.json({ plans: plans.map(({ _count, ...p }) => ({ ...p, tenantCount: _count.tenants })) });
  }),
);

planRouter.post(
  '/',
  asyncHandler(async (req: Request, res: Response) => {
    const input = createSchema.parse(req.body);
    bedsCoverProperties(input.maxProperties, input.maxBeds);
    const clash = await prismaUnscoped.plan.findUnique({ where: { name: input.name } });
    if (clash) throw new ConflictError('A plan with that name already exists');
    if (input.isDefault) await prismaUnscoped.plan.updateMany({ data: { isDefault: false } });
    const plan = await prismaUnscoped.plan.create({ data: input });
    res.status(201).json({ plan });
  }),
);

planRouter.patch(
  '/:id',
  asyncHandler(async (req: Request, res: Response) => {
    const input = updateSchema.parse(req.body);
    const existing = await prismaUnscoped.plan.findUnique({ where: { id: req.params.id }, include: { tenants: { select: { id: true, name: true } } } });
    if (!existing) throw new NotFoundError('Plan not found');
    const next = {
      maxProperties: input.maxProperties !== undefined ? input.maxProperties : existing.maxProperties,
      maxBeds: input.maxBeds !== undefined ? input.maxBeds : existing.maxBeds,
    };
    bedsCoverProperties(next.maxProperties, next.maxBeds);
    // Lowering a limit below what a tenant on the plan already has would leave
    // them over it with no way back; move them to a bigger plan first.
    if (input.maxProperties !== undefined || input.maxBeds !== undefined) {
      const over: string[] = [];
      for (const t of existing.tenants) {
        const why = planShortfall(next, await tenantUsage(t.id));
        if (why) over.push(`${t.name} has ${why}`);
      }
      if (over.length) throw new ConflictError(`That would put tenants over the limit: ${over.join('; ')}. Move them to a bigger plan first.`, 'PLAN_BELOW_USAGE');
    }
    if (input.name && input.name !== existing.name) {
      const clash = await prismaUnscoped.plan.findUnique({ where: { name: input.name } });
      if (clash) throw new ConflictError('A plan with that name already exists');
    }
    // Only one plan can be the default for new tenants.
    if (input.isDefault) await prismaUnscoped.plan.updateMany({ data: { isDefault: false } });
    const plan = await prismaUnscoped.plan.update({ where: { id: req.params.id }, data: input });
    res.json({ plan });
  }),
);

planRouter.delete(
  '/:id',
  asyncHandler(async (req: Request, res: Response) => {
    const plan = await prismaUnscoped.plan.findUnique({
      where: { id: req.params.id },
      include: { _count: { select: { tenants: true } } },
    });
    if (!plan) throw new NotFoundError('Plan not found');
    if (plan._count.tenants > 0) {
      throw new ConflictError(`${plan._count.tenants} tenant(s) are on this plan — move them first`);
    }
    await prismaUnscoped.plan.delete({ where: { id: req.params.id } });
    res.status(204).send();
  }),
);
