import { Request, Response } from 'express';
import { z } from 'zod';
import {
  IDENTITY_NUMBERS,
  createSubAdminSchema,
  resetPasswordSchema,
  updateSubAdminSchema,
  updateMyStaffPhotoSchema,
} from './subadmin.schemas';
import * as subAdminService from './subadmin.service';
import * as salary from './salary.service';
import { getPagination, getSearch } from '../../lib/pagination';
import { Role } from '@prisma/client';
import { ForbiddenError } from '../../lib/errors';

const assignRoleSchema = z.object({ customRoleId: z.string().uuid().nullable() });

const isOwner = (req: Request) => req.user!.role === Role.HOSTEL_ADMIN;
/** PAN, Aadhaar, UAN, PF and ESIC are a hostel admin's to set, as identity documents are. */
function guardIdentityNumbers(req: Request, input: Partial<Record<(typeof IDENTITY_NUMBERS)[number], unknown>>) {
  if (!isOwner(req) && IDENTITY_NUMBERS.some((k) => input[k] !== undefined)) throw new ForbiddenError('Only a hostel admin can change PAN, Aadhaar, UAN, PF or ESIC numbers');
}

export async function createSubAdmin(req: Request, res: Response): Promise<void> {
  const input = await subAdminService.dropRecordWhereOff(createSubAdminSchema.parse(req.body));
  if ((input.monthlySalary != null || input.salaryDay != null) && req.user!.role !== Role.HOSTEL_ADMIN) {
    throw new ForbiddenError('Only a hostel admin can set salaries');
  }
  guardIdentityNumbers(req, input);
  const user = await subAdminService.createSubAdmin(input, req.user!.sub);
  res.status(201).json({ user });
}

export async function subAdminStats(_req: Request, res: Response): Promise<void> {
  res.json({ stats: await subAdminService.subAdminStats() });
}

export async function listSubAdmins(req: Request, res: Response): Promise<void> {
  const pagination = getPagination(req.query);
  const role =
    req.query.role === Role.WARDEN || req.query.role === Role.MESS_ADMIN || req.query.role === Role.GUARD ? req.query.role : undefined;
  const result = await subAdminService.listSubAdmins(pagination, {
    q: getSearch(req.query),
    role,
  }, isOwner(req));
  res.json(pagination ? result : { users: result });
}

export async function assignRole(req: Request, res: Response): Promise<void> {
  const { customRoleId } = assignRoleSchema.parse(req.body);
  res.json({ user: await subAdminService.assignRole(req.params.id, customRoleId, req.user!.sub, isOwner(req)) });
}

export async function getSubAdmin(req: Request, res: Response): Promise<void> {
  res.json({ user: await subAdminService.getSubAdmin(req.params.id, isOwner(req)) });
}

export async function updateMyStaffPhoto(req: Request, res: Response): Promise<void> {
  const { photoUrl } = updateMyStaffPhotoSchema.parse(req.body);
  res.json({ user: await subAdminService.updateMyStaffPhoto(req.user!.sub, photoUrl) });
}

export async function updateSubAdmin(req: Request, res: Response): Promise<void> {
  const input = await subAdminService.dropRecordWhereOff(updateSubAdminSchema.parse(req.body));

  // Identity documents are a hostel admin's to set. MANAGE_STAFF alone opens
  // this route, and a warden holding it may still edit a colleague's name or
  // phone — but not what proves who they are.
  const touchesDocuments = input.idProofUrl !== undefined;
  if (touchesDocuments && req.user!.role !== Role.HOSTEL_ADMIN) {
    throw new ForbiddenError('Only a hostel admin can change identity documents');
  }
  // Pay is the owner's business too (Sprint 6).
  if ((input.monthlySalary !== undefined || input.salaryDay !== undefined) && req.user!.role !== Role.HOSTEL_ADMIN) {
    throw new ForbiddenError('Only a hostel admin can change salaries');
  }
  guardIdentityNumbers(req, input);

  res.json({ user: await subAdminService.updateSubAdmin(req.params.id, input, isOwner(req)) });
}

export async function resetSubAdminPassword(req: Request, res: Response): Promise<void> {
  const { newPassword } = resetPasswordSchema.parse(req.body);
  await subAdminService.resetSubAdminPassword(req.params.id, newPassword);
  res.status(204).send();
}

/** Sprint 6: who gets paid this month and whether it is booked; post it now. Hostel admin only. */
export async function salaryRunPreview(req: Request, res: Response): Promise<void> {
  if (req.user!.role !== Role.HOSTEL_ADMIN) throw new ForbiddenError('Only a hostel admin can see salaries');
  res.json({ run: await salary.salaryPreview(String(req.query.period ?? new Date().toISOString().slice(0, 7))) });
}
export async function salaryRunPost(req: Request, res: Response): Promise<void> {
  if (req.user!.role !== Role.HOSTEL_ADMIN) throw new ForbiddenError('Only a hostel admin can post salaries');
  const { period } = z.object({ period: z.string().optional() }).parse(req.body ?? {});
  res.json({ run: await salary.postSalaries(period ?? new Date().toISOString().slice(0, 7), req.user!.sub) });
}

export async function deleteSubAdmin(req: Request, res: Response): Promise<void> {
  res.json(await subAdminService.deleteSubAdmin(req.params.id));
}
