import { z } from 'zod';
import { INDIAN_STATES } from '../../lib/india';

/**
 * Where the student is from — their home address, distinct from the bed they
 * occupy. Shared by onboarding and editing so the two cannot diverge.
 */
const homeAddress = {
  address: z.string().max(300).optional(),
  city: z.string().max(80).optional(),
  state: z.enum(INDIAN_STATES).optional(),
  /// Indian PIN codes are exactly six digits; anything else is a typo.
  postalCode: z.string().regex(/^\d{6}$/, 'Postal code must be 6 digits').optional(),
};

/**
 * A calendar day.
 *
 * Accepts a full ISO timestamp as well as the plain form, because that is
 * what this API RETURNS: a date column comes back as
 * `2026-09-24T00:00:00.000Z`, so reading a student and saving them back
 * unchanged was refused with "date must be YYYY-MM-DD" — a round trip the
 * API would not accept from itself. The day is kept; the time never meant
 * anything, these columns hold a date.
 */
const dateStr = z
  .string()
  .regex(
    /^\d{4}-\d{2}-\d{2}(T[\d:.]+Z?)?$/,
    'date must be YYYY-MM-DD',
  )
  .transform((v) => v.slice(0, 10));
const method = z.enum(['CASH', 'UPI', 'CARD', 'OTHER']);

/**
 * Compliance and money that come with a new resident. All optional so a
 * hostel that collects the deposit next week can still onboard today.
 */
const compliance = {
  depositAmount: z.coerce.number().int().min(0).max(10_000_000).nullable().optional(),
  depositPaid: z.coerce.number().int().min(0).max(10_000_000).optional(),
  depositPaidAt: dateStr.nullable().optional(),
  depositMethod: method.nullable().optional(),
  depositReference: z.string().trim().max(80).nullable().optional(),
  depositRefunded: z.coerce.number().int().min(0).max(10_000_000).optional(),
  depositRefundedAt: dateStr.nullable().optional(),
  depositNote: z.string().max(200).nullable().optional(),
  kycIdType: z.enum(['AADHAAR', 'PAN', 'PASSPORT', 'VOTER_ID', 'DRIVING_LICENCE']).nullable().optional(),
  kycIdNumber: z.string().trim().min(4).max(30).nullable().optional(),
  kycAddressProofUrl: z.string().max(500).nullable().optional(),
  kycStatus: z.enum(['PENDING', 'VERIFIED']).optional(),
  policeVerificationStatus: z.enum(['NOT_REQUIRED', 'PENDING', 'SUBMITTED', 'VERIFIED']).optional(),
  policeVerificationRef: z.string().max(60).nullable().optional(),
  policeVerificationDate: dateStr.nullable().optional(),
  policeVerificationDocUrl: z.string().max(500).nullable().optional(),
};

/**
 * Sprint 1 (TEPL): the employee's company record. Accepted from every client;
 * the service refuses it unless the tenant has employee records on.
 */
const employeeFields = {
  employeeCode: z.string().trim().min(1).max(40).nullable().optional(),
  cardNumber: z.string().trim().min(1).max(40).nullable().optional(),
  departmentId: z.string().uuid().nullable().optional(),
  contractor: z.string().trim().max(120).nullable().optional(),
  defaultShiftId: z.string().uuid().nullable().optional(),
};

/** YYYY-MM-DD, kept as midnight UTC of that day. */
const dayString = z
  .string()
  .regex(/^\d{4}-\d{2}-\d{2}$/, 'date must be YYYY-MM-DD')
  .transform((v) => new Date(`${v}T00:00:00.000Z`))
  .refine((d) => !Number.isNaN(d.getTime()), 'not a date');

export const onboardStudentSchema = z.object({
  name: z.string().min(2).max(120),
  // Both or neither: a walk-in may be registered with no login at all, in
  // which case the account gets a placeholder address nobody can sign in
  // with. Older clients always send both, so nothing changes for them.
  email: z.string().email().toLowerCase().optional(),
  phone: z.string().min(7).max(20).optional(),
  password: z.string().min(8).max(200).optional(),
  guardianName: z.string().max(120).optional(),
  guardianPhone: z.string().min(7).max(20).optional(),
  parentName: z.string().max(120).optional(),
  parentPhone: z.string().min(7).max(20).optional(),
  ...homeAddress,
  ...compliance,
  ...employeeFields,
  bedId: z.string().uuid().optional(),
  /** Sprint 1 (TEPL): hold the bed until their first punch instead of moving them in now. */
  holdForArrival: z.boolean().optional(),
  idProofUrl: z.string().max(500).optional(), // S3 key from the presign flow
  photoUrl: z.string().max(500).optional(),
  // The day they actually moved in, for pro-rata billing. Omitted means today.
  movedInAt: dayString.optional(),
})
  .refine((v) => (v.email === undefined) === (v.password === undefined), {
    message: 'Send both email and password to create a login, or neither',
    path: ['email'],
  });

/**
 * Manual hostel/PG onboarding is a complete compliance record. Imports use
 * the complete tenant-specific schema; the base schema remains compatible
 * with existing dormitory front-desk clients.
 */
const completeRecord = (opts: { deposit: boolean; contactWord: string; documents?: boolean }) => onboardStudentSchema.superRefine((value, ctx) => {
  const requiredText: Array<[keyof typeof value, string]> = [
    ['phone', 'Phone number is required'],
    ['guardianName', `${opts.contactWord} name is required`],
    ['guardianPhone', `${opts.contactWord} phone is required`],
    ['address', 'Home address is required'],
    ['state', 'State is required'],
    ['city', 'City is required'],
    ['postalCode', 'Postal code is required'],
    ['kycIdNumber', 'ID number is required'],
    ...(opts.documents === false
      ? []
      : ([
          ['idProofUrl', 'ID proof is required'],
          ['photoUrl', 'Photo is required'],
        ] as Array<[keyof typeof value, string]>)),
  ];
  for (const [field, message] of requiredText) {
    const current = value[field];
    if (typeof current !== 'string' || !current.trim()) {
      ctx.addIssue({ code: z.ZodIssueCode.custom, path: [field], message });
    }
  }
  if (opts.deposit && value.depositAmount == null) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['depositAmount'], message: 'Deposit agreed is required' });
  if (opts.deposit && value.depositPaid === undefined) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['depositPaid'], message: 'Received amount is required' });
  if (opts.deposit && !value.depositPaidAt) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['depositPaidAt'], message: 'Received date is required' });
  if (opts.deposit && !value.depositMethod) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['depositMethod'], message: 'Payment method is required' });
  if (!value.kycIdType) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['kycIdType'], message: 'ID type is required' });
  if (!value.kycStatus) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['kycStatus'], message: 'KYC status is required' });
  if (!value.movedInAt) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['movedInAt'], message: 'Moved-in date is required' });
});

export const hostelOnboardStudentSchema = completeRecord({ deposit: true, contactWord: 'Guardian' });
/**
 * An employee hostel (3 Nov 2026): the same complete record, with an
 * emergency contact instead of a guardian and no security deposit — the
 * company houses its own staff.
 */
export const employeeOnboardStudentSchema = completeRecord({ deposit: false, contactWord: 'Emergency contact' });
/**
 * Sprint 1 (TEPL): an employee hostel's sheet import. The company's HR holds
 * each employee's ID proof and photo, so a sheet of hundreds need not carry
 * two files a row; they can be added on the employee's page later.
 */
export const employeeImportStudentSchema = completeRecord({ deposit: false, contactWord: 'Emergency contact', documents: false });

/** Import-only complete customer record; dormitory guardians remain optional. */
export const dormitoryImportStudentSchema = onboardStudentSchema.superRefine((value, ctx) => {
  const requiredText: Array<[keyof typeof value, string]> = [
    ['phone', 'Phone number is required'],
    ['address', 'Home address is required'],
    ['state', 'State is required'],
    ['city', 'City is required'],
    ['postalCode', 'Postal code is required'],
    ['kycIdNumber', 'ID number is required'],
    ['idProofUrl', 'ID proof is required'],
    ['photoUrl', 'Photo is required'],
  ];
  for (const [field, message] of requiredText) {
    const current = value[field];
    if (typeof current !== 'string' || !current.trim()) ctx.addIssue({ code: z.ZodIssueCode.custom, path: [field], message });
  }
  if (value.depositAmount == null) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['depositAmount'], message: 'Deposit agreed is required' });
  if (value.depositPaid === undefined) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['depositPaid'], message: 'Received amount is required' });
  if (value.depositAmount != null && value.depositPaid !== undefined && value.depositPaid > value.depositAmount) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['depositPaid'], message: 'Received amount cannot exceed the agreed deposit' });
  if (!value.depositPaidAt) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['depositPaidAt'], message: 'Received date is required' });
  if (!value.depositMethod) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['depositMethod'], message: 'Payment method is required' });
  if (!value.kycIdType) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['kycIdType'], message: 'ID type is required' });
  if (!value.kycStatus) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['kycStatus'], message: 'KYC status is required' });
  if (!value.movedInAt) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['movedInAt'], message: 'Moved-in date is required' });
});

/** Giving a login to someone registered without one. */
export const createStudentLoginSchema = z.object({
  email: z.string().email().toLowerCase(),
  password: z.string().min(8, 'Password must be at least 8 characters').max(200),
});

/**
 * Correcting a student's details after onboarding.
 *
 * Every field is optional: omit one to leave it alone, send null to clear it.
 * Name, email and phone live on the User, the rest on the profile.
 *
 * Password stays out — that is theirs to change, or an admin's to reset
 * through the dedicated reset route. Email is in by product decision: a hostel
 * admin corrects a mistyped sign-in address, so it is checked for uniqueness
 * in the service before it is written.
 */
export const updateStudentSchema = z
  .object({
    name: z.string().min(2).max(120).optional(),
    // Changing it changes how the student signs in, so it is checked for
    // uniqueness in the service before it is written.
    email: z.string().email().toLowerCase().optional(),
    phone: z.string().min(7).max(20).nullable().optional(),
    guardianName: z.string().max(120).nullable().optional(),
    guardianPhone: z.string().min(7).max(20).nullable().optional(),
    parentName: z.string().max(120).nullable().optional(),
    parentPhone: z.string().min(7).max(20).nullable().optional(),
    address: z.string().max(300).nullable().optional(),
    city: z.string().max(80).nullable().optional(),
    state: z.enum(INDIAN_STATES).nullable().optional(),
    postalCode: z.string().regex(/^\d{6}$/, 'Postal code must be 6 digits').nullable().optional(),
    // S3 keys from the presign flow, as on onboarding.
    idProofUrl: z.string().max(500).nullable().optional(),
    photoUrl: z.string().max(500).nullable().optional(),
    ...compliance,
    ...employeeFields,
  })
  .refine((v) => Object.keys(v).length > 0, 'Nothing to update');

export type UpdateStudentInput = z.infer<typeof updateStudentSchema>;

export const assignBedSchema = z.object({
  // null moves the student out of their bed without deleting them.
  bedId: z.string().uuid().nullable(),
  // The day of the move, for pro-rata billing: move-in when a bed is given,
  // move-out when bedId is null. Omitted means today.
  movedInAt: dayString.optional(),
  vacatedAt: dayString.optional(),
  /// Dormitories: both present books a stay (planned check-in and check-out) instead of a plain move-in.
  checkIn: z.string().datetime().optional(),
  /// With a dormitory booking: a custom charge instead of nights × rate.
  amount: z.number().int().min(0).max(10_000_000).optional(),
  checkOut: z.string().datetime().optional(),
});


export type OnboardStudentInput = z.infer<typeof onboardStudentSchema>;

/** Query filters for the student list. Search and pagination are shared. */
export const listStudentsQuerySchema = z.object({
  // Sent as a string over the wire; coerced so `?assigned=false` works.
  assigned: z
    .enum(['true', 'false'])
    .optional()
    .transform((v) => (v === undefined ? undefined : v === 'true')),
});

/// A student replacing their own photo. Null clears it.
export const updateMyPhotoSchema = z.object({
  photoUrl: z.string().max(500).nullable(),
});

/// Staff setting a new password for a student who cannot sign in.
export const resetStudentPasswordSchema = z.object({
  newPassword: z.string().min(8, 'Password must be at least 8 characters').max(200),
});
