import { z } from 'zod';
import { TenantKind, TenantPlan } from '@prisma/client';
import { propertyDetailsSchema } from '../properties/property.schemas';
import { PLAN_CYCLES } from './tenant-access.service';

export const createTenantSchema = z.object({
  name: z.string().min(2).max(120),
  /** Hostel, PG or dormitory. Older clients omit it and get a hostel. */
  kind: z.nativeEnum(TenantKind).optional(),
  /** Preferred: a custom Plan id. Omit to use the plan marked as default. */
  planId: z.string().uuid().optional(),
  /** Legacy fixed tier — accepted for backwards compatibility. */
  plan: z.nativeEnum(TenantPlan).optional(),
  hostelAdmin: z.object({
    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),
  }),
  /**
   * The tenant's first property, created with the account. Optional so older
   * clients keep working: omit it and a "Main Property" is created as before,
   * which is what the properties list used to do lazily on first access.
   */
  property: propertyDetailsSchema.extend({ name: z.string().min(2).max(120).optional() }).optional(),
  /**
   * How the hostel gets access, from today: a free trial of N days, or a paid
   * plan for a billing cycle. Older clients omit it and get a 14-day trial.
   */
  access: z
    .discriminatedUnion('kind', [
      z.object({ kind: z.literal('TRIAL'), trialDays: z.number().int('Whole days').min(1, 'At least 1 day').max(365, 'At most 365 days') }),
      z.object({ kind: z.literal('PLAN'), planId: z.string().uuid(), cycle: z.enum(PLAN_CYCLES), raiseInvoice: z.boolean().optional() }),
    ])
    .optional(),
});

export const renewSchema = z
  .object({
    planId: z.string().uuid(),
    cycle: z.enum(PLAN_CYCLES).nullable().optional(),
    /** A custom last day for a special deal, instead of a cycle. */
    endsOn: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Use a YYYY-MM-DD date').nullable().optional(),
    raiseInvoice: z.boolean().optional(),
  })
  .refine((v) => !!v.cycle !== !!v.endsOn, 'Pick a billing cycle or an end date, not both');

export const extendTrialSchema = z.object({ days: z.number().int('Whole days').min(1, 'At least 1 day').max(365, 'At most 365 days') });

export const setPlanSchema = z.object({
  planId: z.string().uuid().nullable(),
});

export type CreateTenantInput = z.infer<typeof createTenantSchema>;

export const updateTenantSchema = z
  .object({
    name: z.string().min(2).max(120).optional(),
    planId: z.string().uuid().nullable().optional(),
    kind: z.nativeEnum(TenantKind).optional(),
  })
  .refine((v) => v.name !== undefined || v.planId !== undefined || v.kind !== undefined, 'Nothing to update');

export const suspendTenantSchema = z.object({
  reason: z.string().max(200).optional(),
});

/** Deleting a tenant requires echoing its exact name — no accidental clicks. */
export const deleteTenantSchema = z.object({
  confirmName: z.string().min(1),
});

export type UpdateTenantInput = z.infer<typeof updateTenantSchema>;
