import { Meal, MessBillingMode } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { isValidPeriod } from '../../lib/period';
import { billableDays, dayFrom, monthDays } from './calendar.service';

/**
 * Student meal opt-out (Sprint 6).
 *
 * The admin's whole-day mark (MessAttendance) stays exactly as it was. This
 * adds a second, student-owned record: "I will skip dinner on the 14th". It
 * is off until the hostel enables it, and bounded by a cutoff on the day
 * before, so the kitchen's headcount for tomorrow is known tonight and nobody
 * is marked off after the bill lands.
 *
 * Two knobs make it fit both PG and college rules:
 *   meal weights        — what share of a day's fee each meal carries;
 *   minimum rebate days — a run of whole days that must be at least this long
 *                         before it reduces the bill (1 = every meal counts).
 */

export const MEALS: Meal[] = [Meal.BREAKFAST, Meal.LUNCH, Meal.DINNER];

export interface OptOutRules {
  enabled: boolean;
  cutoff: string;
  minRebateDays: number;
  weights: { BREAKFAST: number; LUNCH: number; DINNER: number };
}

export async function optOutRules(): Promise<OptOutRules> {
  const s = await db.tenantSettings.findFirst({
    select: { messOptOutEnabled: true, messOptOutCutoff: true, messMinRebateDays: true, messBreakfastWeight: true, messLunchWeight: true, messDinnerWeight: true },
  });
  return {
    enabled: s?.messOptOutEnabled ?? false,
    cutoff: s?.messOptOutCutoff ?? '20:00',
    minRebateDays: s?.messMinRebateDays ?? 1,
    weights: { BREAKFAST: s?.messBreakfastWeight ?? 20, LUNCH: s?.messLunchWeight ?? 40, DINNER: s?.messDinnerWeight ?? 40 },
  };
}

/** The moment after which a meal on `dateStr` can no longer be changed: the cutoff, IST, the day before. */
export function mealDeadline(dateStr: string, cutoff: string): Date {
  const day = dayFrom(dateStr);
  const prev = new Date(day.getTime() - 86_400_000).toISOString().slice(0, 10);
  return new Date(`${prev}T${cutoff}:00+05:30`);
}

async function myProfile(userId: string) {
  const profile = await db.studentProfile.findFirst({ where: { userId }, select: { id: true, tenantId: true } });
  if (!profile) throw new NotFoundError('No student profile for this account');
  return profile;
}

/** The student's own opt-outs for a month, with what the month would come to. */
export async function myOptOuts(userId: string, period: string) {
  if (!isValidPeriod(period)) throw new BadRequestError('period (YYYY-MM) is required');
  const profile = await myProfile(userId);
  const rules = await optOutRules();
  const { start, end } = monthDays(period);
  const rows = await db.messMealOptOut.findMany({ where: { studentProfileId: profile.id, date: { gte: start, lte: end } }, orderBy: { date: 'asc' } });
  const byDate = new Map<string, Meal[]>();
  for (const r of rows) {
    const k = r.date.toISOString().slice(0, 10);
    byDate.set(k, [...(byDate.get(k) ?? []), r.meal]);
  }

  // What the bill would be, so the student sees the effect of a toggle rather
  // than guessing. Under actual-cost the rate is unknown until month end.
  const settings = await db.tenantSettings.findFirst({ select: { messBillingMode: true, messMonthlyFee: true, messDailyRate: true } });
  const mode = settings?.messBillingMode ?? MessBillingMode.FIXED_MONTHLY;
  const days = await billableDays(period);
  const billed = days.byStudent.get(profile.id) ?? 0;
  const onMess = days.byStudent.has(profile.id);
  let dailyRate: number | null = null;
  if (mode === MessBillingMode.FIXED_MONTHLY && settings?.messMonthlyFee && days.openDays > 0) dailyRate = settings.messMonthlyFee / days.openDays;
  else if (mode === MessBillingMode.PER_DAY && settings?.messDailyRate) dailyRate = settings.messDailyRate;

  return {
    ...rules,
    period,
    onMess,
    days: [...byDate.entries()].map(([date, meals]) => ({ date, meals })),
    billing: {
      mode,
      openDays: days.openDays,
      billedDays: Math.round(billed * 100) / 100,
      dailyRate: dailyRate == null ? null : Math.round(dailyRate * 100) / 100,
      estimate: dailyRate == null ? null : Math.round(dailyRate * billed),
    },
  };
}

/** Set which meals the student will skip on one day. `true` = skipping. */
export async function setMyOptOut(userId: string, input: { date: string; meals: Partial<Record<Meal, boolean>> }, now = new Date()) {
  const tenantId = getTenantIdOrThrow();
  const profile = await myProfile(userId);
  const rules = await optOutRules();
  if (!rules.enabled) throw new ConflictError('Your hostel has not switched on meal opt-out. Ask the mess admin to mark you off instead.', 'OPT_OUT_DISABLED');

  const date = dayFrom(input.date);
  const deadline = mealDeadline(input.date, rules.cutoff);
  if (now >= deadline) {
    const when = deadline.toLocaleString('en-IN', { day: 'numeric', month: 'short', hour: 'numeric', minute: '2-digit', timeZone: 'Asia/Kolkata' });
    throw new BadRequestError(`Too late to change ${input.date} — the cutoff was ${when}.`, 'OPT_OUT_CUTOFF');
  }
  const sub = await db.messSubscription.findFirst({ where: { studentProfileId: profile.id, startDate: { lte: date }, OR: [{ endDate: null }, { endDate: { gte: date } }] } });
  if (!sub) throw new BadRequestError('You are not on the mess for that day');
  const holiday = await db.messDay.findFirst({ where: { date, isHoliday: true }, select: { id: true } });
  if (holiday) throw new BadRequestError('The mess is closed that day — nobody is billed for it');

  for (const meal of MEALS) {
    const want = input.meals[meal];
    if (want === undefined) continue;
    const existing = await db.messMealOptOut.findFirst({ where: { studentProfileId: profile.id, date, meal } });
    if (want && !existing) await db.messMealOptOut.create({ data: { tenantId, studentProfileId: profile.id, date, meal } });
    if (!want && existing) await db.messMealOptOut.delete({ where: { id: existing.id } });
  }
  const rows = await db.messMealOptOut.findMany({ where: { studentProfileId: profile.id, date } });
  return { date: input.date, meals: rows.map((r) => r.meal), deadline };
}

/**
 * How many plates the kitchen should cook on a date: everyone on the mess
 * that day, minus the admin's day-offs, minus each meal's opt-outs. Zero on a
 * holiday. Optionally one property's students only.
 */
export async function headcount(dateStr: string, propertyId?: string) {
  const date = dayFrom(dateStr);
  const holiday = await db.messDay.findFirst({ where: { date, isHoliday: true }, select: { id: true } });
  const subs = await db.messSubscription.findMany({
    where: { startDate: { lte: date }, OR: [{ endDate: null }, { endDate: { gte: date } }], ...(propertyId ? { student: { propertyId } } : {}) },
    select: { studentProfileId: true },
  });
  const ids = [...new Set(subs.map((s) => s.studentProfileId))];
  const absent = new Set((await db.messAttendance.findMany({ where: { date, present: false, studentProfileId: { in: ids } }, select: { studentProfileId: true } })).map((a) => a.studentProfileId));
  const eating = ids.filter((id) => !absent.has(id));
  const optOuts = await db.messMealOptOut.findMany({ where: { date, studentProfileId: { in: eating } }, select: { meal: true } });
  const off = { BREAKFAST: 0, LUNCH: 0, DINNER: 0 };
  for (const o of optOuts) off[o.meal]++;
  const base = holiday ? 0 : eating.length;
  return {
    date: dateStr,
    holiday: !!holiday,
    onMess: ids.length,
    dayOff: absent.size,
    breakfast: holiday ? 0 : base - off.BREAKFAST,
    lunch: holiday ? 0 : base - off.LUNCH,
    dinner: holiday ? 0 : base - off.DINNER,
    optedOut: off,
  };
}
