import { db } from '../../lib/prisma';
import { paginated, type Pagination } from '../../lib/pagination';
import { getTenantContext, getTenantIdOrThrow } from '../../lib/tenantContext';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { BadRequestError, NotFoundError } from '../../lib/errors';

/**
 * The dated mess calendar.
 *
 * MessMenu is a weekly TEMPLATE (Monday's lunch, and so on). MessDay is what
 * is actually being served on a given date, and whether the kitchen is shut.
 * Filling a month is "stamp the template, then edit the days that differ" —
 * without the template that is ninety meals typed by hand, and without dated
 * rows there is nowhere to put a holiday or a festival menu.
 *
 * A holiday means nobody eats, so nobody is billed for it. That single rule is
 * what makes the calendar worth keeping accurate.
 */

/** UTC midnight for a YYYY-MM-DD, matching the @db.Date columns. */
export function dayFrom(dateStr: string): Date {
  const d = new Date(`${dateStr}T00:00:00.000Z`);
  if (Number.isNaN(d.getTime())) throw new BadRequestError('Invalid date');
  return d;
}

export function monthDays(period: string): { start: Date; end: Date; days: Date[] } {
  const [y, m] = period.split('-').map(Number);
  if (!y || !m || m < 1 || m > 12) throw new BadRequestError('period must be YYYY-MM');
  const count = new Date(Date.UTC(y, m, 0)).getUTCDate();
  const days = Array.from({ length: count }, (_, i) => new Date(Date.UTC(y, m - 1, i + 1)));
  return { start: days[0], end: days[days.length - 1], days };
}

export async function getCalendar(period: string) {
  const { start, end, days } = monthDays(period);
  const rows = await db.messDay.findMany({ where: { date: { gte: start, lte: end } }, orderBy: { date: 'asc' } });
  const byDate = new Map(rows.map((r) => [r.date.toISOString().slice(0, 10), r]));
  // Enterprise only: snacks live on the weekly menu, not on the dated day. Other kinds get no such field.
  const context = getTenantContext();
  const snacksOn = !!context?.tenantId && (await tenantHasFeature(context.tenantId, 'canteen'));
  const weekly = snacksOn ? await db.messMenu.findMany({ select: { dayOfWeek: true, snacks: true } }) : [];
  const snacksOf = new Map(weekly.map((w) => [w.dayOfWeek, w.snacks]));

  // Every day of the month is returned, present in the table or not, so the
  // client renders a full grid without inventing the gaps itself.
  return days.map((d) => {
    const key = d.toISOString().slice(0, 10);
    const row = byDate.get(key);
    return {
      date: key,
      dayOfWeek: d.getUTCDay(),
      breakfast: row?.breakfast ?? null,
      lunch: row?.lunch ?? null,
      dinner: row?.dinner ?? null,
      isHoliday: row?.isHoliday ?? false,
      note: row?.note ?? null,
      planned: !!row,
      ...(snacksOn ? { snacks: row?.isHoliday ? null : snacksOf.get(d.getUTCDay()) ?? null } : {}),
    };
  });
}

export async function setDay(
  dateStr: string,
  data: { breakfast?: string | null; lunch?: string | null; dinner?: string | null; isHoliday?: boolean; note?: string | null },
) {
  const tenantId = getTenantIdOrThrow();
  const date = dayFrom(dateStr);
  const existing = await db.messDay.findFirst({ where: { date } });
  if (existing) return db.messDay.update({ where: { id: existing.id }, data });
  return db.messDay.create({ data: { tenantId, date, ...data } });
}

/**
 * Stamp the weekly template across a month.
 *
 * `overwrite: false` (the default) fills only the days nobody has touched, so
 * running it twice cannot wipe the festival menu someone typed by hand.
 * Holidays are never overwritten either way — a closed kitchen is a decision,
 * not a gap to be filled.
 */
export async function applyTemplate(period: string, overwrite: boolean) {
  const tenantId = getTenantIdOrThrow();
  const template = await db.messMenu.findMany({});
  if (template.length === 0) throw new BadRequestError('Set the weekly menu template first');
  const byDow = new Map(template.map((t) => [t.dayOfWeek, t]));

  const { start, end, days } = monthDays(period);
  const existing = await db.messDay.findMany({ where: { date: { gte: start, lte: end } } });
  const byDate = new Map(existing.map((r) => [r.date.toISOString().slice(0, 10), r]));

  let filled = 0;
  for (const date of days) {
    const key = date.toISOString().slice(0, 10);
    const row = byDate.get(key);
    if (row?.isHoliday) continue;
    const meals = byDow.get(date.getUTCDay());
    if (!meals) continue;
    const data = { breakfast: meals.breakfast, lunch: meals.lunch, dinner: meals.dinner };

    if (!row) {
      await db.messDay.create({ data: { tenantId, date, ...data } });
      filled++;
    } else if (overwrite) {
      await db.messDay.update({ where: { id: row.id }, data });
      filled++;
    }
  }
  return { filled };
}

/** Mark a run of dates as holidays (or clear them) in one call. */
export async function setHolidays(from: string, to: string, isHoliday: boolean, note?: string) {
  const tenantId = getTenantIdOrThrow();
  const start = dayFrom(from);
  const end = dayFrom(to);
  if (end < start) throw new BadRequestError('The end date is before the start date');
  const span = Math.round((end.getTime() - start.getTime()) / 86_400_000) + 1;
  // A range of more than a term is a typo, not a holiday.
  if (span > 120) throw new BadRequestError('That range is too long — mark at most 120 days at a time');

  let changed = 0;
  for (let i = 0; i < span; i++) {
    const date = new Date(start.getTime() + i * 86_400_000);
    const existing = await db.messDay.findFirst({ where: { date } });
    if (existing) await db.messDay.update({ where: { id: existing.id }, data: { isHoliday, note: note ?? existing.note } });
    else await db.messDay.create({ data: { tenantId, date, isHoliday, note } });
    changed++;
  }
  return { changed };
}

// ── Subscriptions ─────────────────────────────────────────────────────────

/**
 * Opt a student in from a date. Re-subscribing while already active is a
 * no-op rather than an error — the intent is "they are on the mess", and two
 * overlapping rows would double-count their billable days.
 */
export async function subscribe(studentProfileId: string, startDate: string) {
  const tenantId = getTenantIdOrThrow();
  const student = await db.studentProfile.findFirst({ where: { id: studentProfileId } });
  if (!student) throw new NotFoundError('Student not found');

  const open = await db.messSubscription.findFirst({ where: { studentProfileId, endDate: null } });
  if (open) return open;
  return db.messSubscription.create({ data: { tenantId, studentProfileId, startDate: dayFrom(startDate) } });
}

/** Close the open subscription on a date. Billing counts up to and including it. */
export async function unsubscribe(studentProfileId: string, endDate: string) {
  const open = await db.messSubscription.findFirst({ where: { studentProfileId, endDate: null } });
  if (!open) throw new NotFoundError('That student is not on the mess');
  const end = dayFrom(endDate);
  if (end < open.startDate) throw new BadRequestError('The end date is before they joined the mess');
  return db.messSubscription.update({ where: { id: open.id }, data: { endDate: end } });
}

/** Every student, with whether they are on the mess right now. */
/**
 * Residents of a property (or the tenant) with an open subscription, and how
 * many residents there are: the same rule as `subscribed=true` on the list,
 * counted rather than listed.
 */
export async function countSubscribers(propertyId?: string) {
  const base = propertyId ? { propertyId } : {};
  const [subscribed, total] = await Promise.all([
    db.studentProfile.count({ where: { ...base, messSubscriptions: { some: { endDate: null } } } }),
    db.studentProfile.count({ where: base }),
  ]);
  return { subscribed, total };
}

export async function listSubscribers(
  propertyId?: string,
  filters?: { q?: string; subscribed?: boolean },
  pagination?: Pagination | null,
) {
  const where = {
    ...(propertyId ? { propertyId } : {}),
    ...(filters?.q
      ? { user: { is: { name: { contains: filters.q, mode: 'insensitive' as const } } } }
      : {}),
    // An open subscription is one with no end date. Asked of the database
    // rather than of the page, or narrowing to "on the mess" would only ever
    // search the twenty rows already fetched.
    ...(filters?.subscribed === true ? { messSubscriptions: { some: { endDate: null } } } : {}),
    ...(filters?.subscribed === false ? { messSubscriptions: { none: { endDate: null } } } : {}),
  };
  const include = {
    user: { select: { id: true, name: true, email: true } },
    messSubscriptions: { orderBy: { startDate: 'desc' as const } },
  };
  const orderBy = { createdAt: 'desc' as const };

  type Row = {
    id: string;
    user: { id: string; name: string; email: string };
    messSubscriptions: { endDate: Date | null; startDate: Date }[];
  };

  const shape = (rows: Row[]) =>
    rows.map(({ messSubscriptions, ...s }) => {
      const open = messSubscriptions.find((x) => x.endDate === null) ?? null;
      return {
        id: s.id,
        user: s.user,
        subscribed: !!open,
        since: open?.startDate ?? null,
        history: messSubscriptions,
      };
    });

  if (!pagination) {
    return shape(await db.studentProfile.findMany({ where, include, orderBy }));
  }

  const [items, total] = await Promise.all([
    db.studentProfile.findMany({
      where,
      include,
      orderBy,
      skip: pagination.skip,
      take: pagination.limit,
    }),
    db.studentProfile.count({ where }),
  ]);
  return paginated(shape(items), total, pagination);
}

/**
 * Days in the month a student is actually liable for.
 *
 * billable = days they were subscribed
 *          − days the kitchen was shut
 *          − days the admin marked them off
 *          − (Sprint 6, when opt-out is on) the meals they opted out of,
 *            weighted — so a skipped dinner is 0.4 of a day, not a whole one.
 *
 * Under a minimum-rebate rule (messMinRebateDays > 1) only runs of WHOLE days
 * at least that long reduce the bill; single meals still inform the kitchen's
 * headcount but are not rebated. That is the college rule — "four days away,
 * tell us in advance, and the mess fee comes off".
 *
 * The same count drives every billing mode, so the three cannot disagree about
 * who ate when. Fractional once opt-out is on; whole days until then.
 */
export async function billableDays(period: string) {
  const { start, end, days } = monthDays(period);

  const [holidays, subs, absences, settings] = await Promise.all([
    db.messDay.findMany({ where: { date: { gte: start, lte: end }, isHoliday: true }, select: { date: true } }),
    db.messSubscription.findMany({ where: { startDate: { lte: end }, OR: [{ endDate: null }, { endDate: { gte: start } }] } }),
    db.messAttendance.findMany({ where: { date: { gte: start, lte: end }, present: false } }),
    db.tenantSettings.findFirst({ select: { messOptOutEnabled: true, messMinRebateDays: true, messBreakfastWeight: true, messLunchWeight: true, messDinnerWeight: true } }),
  ]);
  const optOutOn = settings?.messOptOutEnabled ?? false;
  const minRun = Math.max(1, settings?.messMinRebateDays ?? 1);
  const weight = { BREAKFAST: settings?.messBreakfastWeight ?? 20, LUNCH: settings?.messLunchWeight ?? 40, DINNER: settings?.messDinnerWeight ?? 40 };
  const optOuts = optOutOn ? await db.messMealOptOut.findMany({ where: { date: { gte: start, lte: end } } }) : [];

  const holidayKeys = new Set(holidays.map((h) => h.date.toISOString().slice(0, 10)));
  const openDays = days.filter((d) => !holidayKeys.has(d.toISOString().slice(0, 10)));

  const absentBy = new Map<string, Set<string>>();
  for (const a of absences) {
    const set = absentBy.get(a.studentProfileId) ?? new Set<string>();
    set.add(a.date.toISOString().slice(0, 10));
    absentBy.set(a.studentProfileId, set);
  }
  // student → date → meals skipped
  const optBy = new Map<string, Map<string, Set<'BREAKFAST' | 'LUNCH' | 'DINNER'>>>();
  for (const o of optOuts) {
    const perStudent = optBy.get(o.studentProfileId) ?? new Map();
    const key = o.date.toISOString().slice(0, 10);
    const set = perStudent.get(key) ?? new Set();
    set.add(o.meal);
    perStudent.set(key, set);
    optBy.set(o.studentProfileId, perStudent);
  }
  /** How long the run of whole-day opt-outs containing `key` is, for one student. */
  const runLength = (perStudent: Map<string, Set<string>>, key: string) => {
    const full = (k: string) => (perStudent.get(k)?.size ?? 0) === 3 && !holidayKeys.has(k);
    const step = (k: string, by: number) => new Date(new Date(`${k}T00:00:00.000Z`).getTime() + by * 86_400_000).toISOString().slice(0, 10);
    let n = 1;
    for (let k = step(key, -1); full(k); k = step(k, -1)) n++;
    for (let k = step(key, 1); full(k); k = step(k, 1)) n++;
    return n;
  };

  const byStudent = new Map<string, number>();
  let optOutDays = 0;
  for (const sub of subs) {
    const from = sub.startDate > start ? sub.startDate : start;
    const to = sub.endDate && sub.endDate < end ? sub.endDate : end;
    const absent = absentBy.get(sub.studentProfileId) ?? new Set<string>();
    const perStudent = optBy.get(sub.studentProfileId);
    let count = 0;
    for (const d of openDays) {
      if (d < from || d > to) continue;
      const key = d.toISOString().slice(0, 10);
      if (absent.has(key)) continue;
      const meals = perStudent?.get(key);
      if (!meals || meals.size === 0) {
        count += 1;
      } else if (meals.size === 3 && runLength(perStudent!, key) >= minRun) {
        optOutDays += 1; // a whole day off, long enough to count
      } else if (minRun <= 1) {
        const off = [...meals].reduce((n, m) => n + weight[m], 0) / 100;
        count += Math.max(0, 1 - off);
        optOutDays += Math.min(1, off);
      } else {
        count += 1; // partial, under a minimum-days rule: fed to the kitchen count, not the bill
      }
    }
    byStudent.set(sub.studentProfileId, Math.round(((byStudent.get(sub.studentProfileId) ?? 0) + count) * 100) / 100);
  }

  return {
    openDays: openDays.length,
    totalDays: days.length,
    holidays: days.length - openDays.length,
    byStudent,
    /** Total man-days eaten — the denominator under ACTUAL_COST. */
    manDays: Math.round([...byStudent.values()].reduce((n, v) => n + v, 0) * 100) / 100,
    /** Day-equivalents students took off themselves (Sprint 6); 0 when opt-out is off. */
    optOutDays: Math.round(optOutDays * 100) / 100,
  };
}
