import { Prisma, SubscriptionInvoiceType, TenantAccessKind, TenantStatus } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { env } from '../../config/env';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { sendEmail, emailFailed } from '../../lib/email';
import { accessPausedEmail } from '../../lib/email-templates';
import { planShortfall, tenantUsage } from '../plans/plan-limits';
import { buyerParty, createInvoice, sellerParty } from '../subscriptions/subscriptions.service';

/**
 * A hostel's access window (10 Oct 2026).
 *
 * At creation the super admin gives a hostel either a free trial of N days or
 * a paid plan for a billing cycle (monthly, quarterly, half-yearly, yearly),
 * starting the day it is created. Access lasts through `accessEndsOn`; from
 * midnight India time the day after, the hostel is suspended — which blocks
 * every sign-in for it, students and guardians included (assertTenantActive
 * in auth). Renewing a plan or extending a trial moves the end date and, if
 * the hostel was suspended because it ran out, restores it at once.
 *
 * Dates are India calendar days, stored at noon UTC like invoice periods, so
 * the stored instant always reads back as the same day.
 */

export const CYCLE_MONTHS: Partial<Record<SubscriptionInvoiceType, number>> = {
  MONTHLY: 1,
  QUARTERLY: 3,
  HALF_YEARLY: 6,
  YEARLY: 12,
};
export const PLAN_CYCLES = ['MONTHLY', 'QUARTERLY', 'HALF_YEARLY', 'YEARLY'] as const;
export type PlanCycle = (typeof PLAN_CYCLES)[number];
export const DEFAULT_TRIAL_DAYS = 14;

/**
 * "Now" for a request: the real time, or — only under the test clock, never
 * in production — the X-Test-Now header, so the suites can act on a hostel
 * at the simulated date they suspended it on.
 */
export function clockOf(headers: Record<string, string | string[] | undefined>) {
  const v = headers['x-test-now'];
  if (env.CRM_TEST_CLOCK && env.NODE_ENV !== 'production' && typeof v === 'string' && !Number.isNaN(Date.parse(v))) return new Date(v);
  return new Date();
}

const DAY = 86_400_000;
const IST_MS = 330 * 60_000;

/** Today's India date as YYYY-MM-DD. */
export const istToday = (now = new Date()) => new Date(now.getTime() + IST_MS).toISOString().slice(0, 10);
const atNoon = (d: string) => new Date(`${d}T12:00:00Z`);
const dayOf = (d: Date) => d.toISOString().slice(0, 10);
export const addDays = (d: string, n: number) => dayOf(new Date(Date.parse(`${d}T12:00:00Z`) + n * DAY));

/** Calendar months, clamped (31 Jan + 1 month = 28/29 Feb). */
export function addMonths(d: string, n: number) {
  const [y, m, day] = d.split('-').map(Number);
  const first = new Date(Date.UTC(y, m - 1 + n, 1, 12));
  const last = new Date(Date.UTC(first.getUTCFullYear(), first.getUTCMonth() + 1, 0, 12)).getUTCDate();
  return dayOf(new Date(Date.UTC(first.getUTCFullYear(), first.getUTCMonth(), Math.min(day, last), 12)));
}

/** A cycle starting on `start` covers through the day before the same date `months` later. */
export const cycleEnd = (start: string, cycle: PlanCycle) => addDays(addMonths(start, CYCLE_MONTHS[cycle]!), -1);
/** A trial of N days starting on `start`, the start day included. */
export const trialEnd = (start: string, days: number) => addDays(start, days - 1);

const fmt = (d: string) => new Date(`${d}T12:00:00Z`).toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' });

export type AccessInput = { kind: 'TRIAL'; trialDays: number } | { kind: 'PLAN'; planId: string; cycle: PlanCycle; raiseInvoice?: boolean };

/** The fields a new hostel starts with. Older clients that send nothing get the default trial. */
export function initialAccess(input: AccessInput | undefined, now = new Date()) {
  const start = istToday(now);
  const a = input ?? { kind: 'TRIAL' as const, trialDays: DEFAULT_TRIAL_DAYS };
  if (a.kind === 'TRIAL') {
    return { accessKind: TenantAccessKind.TRIAL, accessStartsOn: atNoon(start), accessEndsOn: atNoon(trialEnd(start, a.trialDays)), trialDays: a.trialDays, planCycle: null };
  }
  return { accessKind: TenantAccessKind.PLAN, accessStartsOn: atNoon(start), accessEndsOn: atNoon(cycleEnd(start, a.cycle)), trialDays: null, planCycle: a.cycle as SubscriptionInvoiceType };
}

/** What the super admin's screens show about a hostel's access. */
export function accessSummary(t: { accessKind: TenantAccessKind | null; accessStartsOn: Date | null; accessEndsOn: Date | null; planCycle: SubscriptionInvoiceType | null; trialDays: number | null; status: TenantStatus; suspendedCause: string | null }, now = new Date()) {
  const endsOn = t.accessEndsOn ? dayOf(t.accessEndsOn) : null;
  const daysLeft = endsOn ? Math.round((Date.parse(`${endsOn}T00:00:00Z`) - Date.parse(`${istToday(now)}T00:00:00Z`)) / DAY) : null;
  return {
    kind: t.accessKind,
    startsOn: t.accessStartsOn ? dayOf(t.accessStartsOn) : null,
    endsOn,
    daysLeft,
    cycle: t.planCycle,
    trialDays: t.trialDays,
    expired: daysLeft !== null && daysLeft < 0,
    suspendedForExpiry: t.status === TenantStatus.SUSPENDED && t.suspendedCause === 'EXPIRED',
  };
}

async function loadTenant(id: string) {
  const t = await prismaUnscoped.tenant.findUnique({ where: { id } });
  if (!t) throw new NotFoundError('Tenant not found');
  return t;
}

/** A hostel that ran out comes back as soon as it has days again. */
const reactivate = (t: { status: TenantStatus; suspendedCause: string | null }) =>
  t.status === TenantStatus.SUSPENDED && t.suspendedCause === 'EXPIRED' ? { status: TenantStatus.ACTIVE, suspendedAt: null, suspendedReason: null, suspendedCause: null } : {};

/**
 * Renew or change the paid plan. The new period starts the day after the
 * current end date if access has not run out yet (nothing is lost), or today
 * if it has; it runs for the cycle, or to a custom end date for a special
 * deal. Optionally raises the matching subscription invoice as a draft.
 */
export async function renewPlan(tenantId: string, input: { planId: string; cycle?: PlanCycle | null; endsOn?: string | null; raiseInvoice?: boolean }, actorId: string, now = new Date()) {
  const t = await loadTenant(tenantId);
  const plan = await prismaUnscoped.plan.findUnique({ where: { id: input.planId } });
  if (!plan) throw new NotFoundError('Plan not found');
  const why = planShortfall(plan, await tenantUsage(tenantId));
  if (why) throw new ConflictError(`The ${plan.name} plan is too small: this tenant already has ${why}. Pick a bigger plan.`, 'PLAN_BELOW_USAGE');
  const today = istToday(now);
  const current = t.accessEndsOn ? dayOf(t.accessEndsOn) : null;
  const start = current && current >= today ? addDays(current, 1) : today;
  let end: string;
  if (input.endsOn) {
    if (input.endsOn < start) throw new BadRequestError(`The end date must be on or after ${fmt(start)}, when this period starts.`);
    end = input.endsOn;
  } else if (input.cycle) {
    end = cycleEnd(start, input.cycle);
  } else throw new BadRequestError('Pick a billing cycle or an end date.');

  const updated = await prismaUnscoped.tenant.update({
    where: { id: tenantId },
    data: { planId: plan.id, accessKind: TenantAccessKind.PLAN, accessStartsOn: atNoon(start), accessEndsOn: atNoon(end), planCycle: input.endsOn ? null : (input.cycle as SubscriptionInvoiceType), trialDays: null, ...reactivate(t) },
  });

  let invoice: { id: string; invoiceNumber: string | null; amount: number } | null = null;
  if (input.raiseInvoice !== false && plan.monthlyPrice > 0) {
    const inv = await createInvoice(
      {
        tenantId,
        invoiceType: input.endsOn ? SubscriptionInvoiceType.ONE_TIME : (input.cycle as SubscriptionInvoiceType),
        ...(input.endsOn ? { subtotal: Math.max(1, Math.round((plan.monthlyPrice * (Date.parse(`${end}T00:00:00Z`) - Date.parse(`${start}T00:00:00Z`) + DAY)) / (30 * DAY))) } : {}),
        issueDate: atNoon(today),
        periodStart: atNoon(start),
        periodEnd: atNoon(end),
        note: `${plan.name} plan, ${fmt(start)} – ${fmt(end)}`,
      },
      actorId,
    );
    invoice = { id: inv.id, invoiceNumber: inv.invoiceNumber, amount: inv.amount };
  }
  return { access: accessSummary(updated, now), reactivated: updated.status === TenantStatus.ACTIVE && t.status === TenantStatus.SUSPENDED, invoice, period: { start, end } };
}

/** Give a hostel on a trial more days: from its end date, or from today if it has run out. */
export async function extendTrial(tenantId: string, days: number, now = new Date()) {
  const t = await loadTenant(tenantId);
  if (t.accessKind === TenantAccessKind.PLAN) throw new ConflictError('This hostel is on a paid plan. Renew the plan instead.', 'NOT_ON_TRIAL');
  const today = istToday(now);
  const current = t.accessEndsOn ? dayOf(t.accessEndsOn) : null;
  const from = current && current >= today ? current : addDays(today, -1);
  const end = addDays(from, days);
  const updated = await prismaUnscoped.tenant.update({
    where: { id: tenantId },
    data: { accessKind: TenantAccessKind.TRIAL, accessStartsOn: t.accessStartsOn ?? atNoon(today), accessEndsOn: atNoon(end), trialDays: (t.trialDays ?? 0) + days, planCycle: null, ...reactivate(t) },
  });
  return { access: accessSummary(updated, now), reactivated: updated.status === TenantStatus.ACTIVE && t.status === TenantStatus.SUSPENDED };
}

/** Manual activation of a hostel whose days have run out would be undone within the hour. */
export async function assertCanActivate(tenantId: string, now = new Date()) {
  const t = await loadTenant(tenantId);
  if (t.accessEndsOn && dayOf(t.accessEndsOn) < istToday(now)) {
    throw new ConflictError(`Its ${t.accessKind === TenantAccessKind.TRIAL ? 'trial' : 'plan'} ended on ${fmt(dayOf(t.accessEndsOn))}. Renew the plan or extend the trial to reactivate it.`, 'ACCESS_EXPIRED');
  }
}

/**
 * The clock's part: suspend every active hostel whose last day has passed,
 * and tell it so — once, logged under the plan reminder log's unique key.
 */
export async function suspendExpired(now = new Date()) {
  const today = istToday(now);
  const due = await prismaUnscoped.tenant.findMany({
    where: { status: TenantStatus.ACTIVE, accessEndsOn: { lt: atNoon(today) } },
    select: { id: true, name: true, accessKind: true, accessEndsOn: true },
  });
  if (!due.length) return 0;
  const seller = await sellerParty();
  let suspended = 0;
  for (const t of due) {
    const endsOn = dayOf(t.accessEndsOn!);
    const what = t.accessKind === TenantAccessKind.TRIAL ? 'Free trial ended' : 'Plan expired';
    // Only flip hostels still active and still past their date (a renewal may have just landed).
    const r = await prismaUnscoped.tenant.updateMany({
      where: { id: t.id, status: TenantStatus.ACTIVE, accessEndsOn: { lt: atNoon(today) } },
      data: { status: TenantStatus.SUSPENDED, suspendedAt: now, suspendedReason: `${what} on ${fmt(endsOn)}`, suspendedCause: 'EXPIRED' },
    });
    if (!r.count) continue;
    suspended++;
    const buyer = await buyerParty(t.id).catch(() => null);
    for (const to of buyer?.recipients ?? []) {
      const mail = accessPausedEmail({ seller, hostelName: t.name, trial: t.accessKind === TenantAccessKind.TRIAL, endedOn: fmt(endsOn) });
      const key = `plan-suspended:${t.id}:${endsOn}:${to.toLowerCase()}`;
      try {
        await prismaUnscoped.planReminderLog.create({ data: { key, kind: 'SUSPENDED', tenantId: t.id, expiresOn: endsOn, toEmail: to, subject: mail.subject.slice(0, 300) } });
      } catch (e) {
        if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') continue;
        throw e;
      }
      const res = await sendEmail(to, mail.subject, mail.text, mail.html);
      await prismaUnscoped.planReminderLog.update({ where: { key }, data: { status: res.mode === 'log' ? 'DRY_RUN' : emailFailed(res) ? 'FAILED' : 'SENT' } });
    }
  }
  return suspended;
}
