import { z } from 'zod';
import { Role } from '@prisma/client';

/** A blank box means "none", so an emptied field clears the value. */
const blank = (v: unknown) => (typeof v === 'string' && v.trim() === '' ? null : v);
const text = (max: number) => z.preprocess(blank, z.string().trim().max(max).nullable().optional());
const upper = (v: unknown) => (typeof v === 'string' ? v.replace(/\s/g, '').toUpperCase() : v);
const digits = (v: unknown) => (typeof v === 'string' ? v.replace(/[\s-]/g, '') : v);
const number = (clean: (v: unknown) => unknown, pattern: RegExp, message: string) => z.preprocess((v) => blank(clean(v)), z.string().regex(pattern, message).nullable().optional());

/**
 * The employment record on a staff member (TEPL, 4 Nov 2026). All optional:
 * uniform dates and police checks come later than the joining day. Numbers
 * are checked for shape only, as nothing here can verify them with the issuer.
 */
export const staffRecordFields = {
  staffCode: text(40),
  plantName: text(80),
  permanentAddress: text(500),
  panNumber: number(upper, /^[A-Z]{5}[0-9]{4}[A-Z]$/, 'PAN is 10 characters, like ABCDE1234F'),
  aadhaarNumber: number(digits, /^[2-9][0-9]{11}$/, 'Aadhaar is 12 digits and does not start with 0 or 1'),
  uanNumber: number(digits, /^[0-9]{12}$/, 'UAN is 12 digits'),
  pfNumber: number(upper, /^[A-Z0-9/-]{5,30}$/, 'Use letters, digits and / for the PF number'),
  esicNumber: number(digits, /^([0-9]{10}|[0-9]{17})$/, 'ESIC is 10 or 17 digits'),
  policeVerification: z.boolean().nullable().optional(),
  medicalFitness: z.boolean().nullable().optional(),
  emergencyContactName: text(120),
  emergencyContactPhone: number(digits, /^\+?[0-9]{7,15}$/, 'Enter a valid emergency contact phone'),
  maritalStatus: z.preprocess(blank, z.enum(['MARRIED', 'UNMARRIED']).nullable().optional()),
  uniformIssuedOn: z.preprocess(blank, z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Uniform issue date must be a date').transform((v) => new Date(`${v}T00:00:00.000Z`)).nullable().optional()),
};

/** Only a hostel admin sets these, as with identity documents. */
export const IDENTITY_NUMBERS = ['panNumber', 'aadhaarNumber', 'uanNumber', 'pfNumber', 'esicNumber'] as const;

/** Hostel Admin may create staff of these roles. A GUARD has one job (the gate). */
export const createSubAdminSchema = z.object({
  role: z.enum([Role.WARDEN, Role.MESS_ADMIN, Role.GUARD]),
  name: z.string().min(2).max(120),
  email: z.string().email().toLowerCase(),
  phone: z.string().min(7).max(20).optional(),
  password: z.string().min(8).max(200),
  /// Sprint 6: rupees per month, and the day of the month it is posted as an expense.
  monthlySalary: z.coerce.number().int().min(0).max(10_000_000).nullable().optional(),
  salaryDay: z.coerce.number().int().min(1).max(28).nullable().optional(),
  ...staffRecordFields,
});

export type CreateSubAdminInput = z.infer<typeof createSubAdminSchema>;

/** Editable fields for an existing staff member. Role may move between the two. */
export const updateSubAdminSchema = z
  .object({
    role: z.enum([Role.WARDEN, Role.MESS_ADMIN, Role.GUARD]),
    name: z.string().min(2).max(120),
    email: z.string().email().toLowerCase(),
    phone: z.union([z.string().min(7).max(20), z.literal('')]),
    // S3 keys from the presign flow. Only a HOSTEL_ADMIN may send these; the
    // route rejects them from anyone else.
    photoUrl: z.string().max(500).nullable(),
    idProofUrl: z.string().max(500).nullable(),
    /// Sprint 6: salary lives on the staff profile; hostel admin only (route check).
    monthlySalary: z.coerce.number().int().min(0).max(10_000_000).nullable(),
    salaryDay: z.coerce.number().int().min(1).max(28).nullable(),
    ...staffRecordFields,
  })
  .partial()
  .refine((v) => Object.keys(v).length > 0, 'Nothing to update');

/// A staff member replacing their own photo. Their documents are not theirs
/// to change, so only the photo is accepted here.
export const updateMyStaffPhotoSchema = z.object({
  photoUrl: z.string().max(500).nullable(),
});

export const resetPasswordSchema = z.object({
  newPassword: z.string().min(8, 'Password must be at least 8 characters').max(200),
});

export type UpdateSubAdminInput = z.infer<typeof updateSubAdminSchema>;
