import { MessBillingMode } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantContext, getTenantIdOrThrow } from '../../lib/tenantContext';
import { monthRange } from '../../lib/period';
import { NotFoundError } from '../../lib/errors';
import { tenantHasFeature } from '../../middleware/requireFeature';

// ── Weekly menu ─────────────────────────────────────────────────────────────
/**
 * Snacks are on the menu for Enterprise tenants only (6 Nov 2026). Everywhere
 * else the field is neither stored nor returned, so those responses are as they
 * were. The canteen module is on for that kind alone.
 */
const snacksHere = async () => {
  const tenantId = getTenantContext()?.tenantId;
  return !!tenantId && tenantHasFeature(tenantId, 'canteen');
};
const forMenu = <T extends { snacks: string | null }>(row: T, snacks: boolean) => {
  if (snacks) return row;
  const { snacks: _snacks, ...others } = row;
  return others;
};

export async function getMenu() {
  const snacks = await snacksHere();
  const rows = await db.messMenu.findMany({ orderBy: { dayOfWeek: 'asc' } });
  return rows.map((r) => forMenu(r, snacks));
}

export async function setMenu(dayOfWeek: number, input: { breakfast?: string | null; lunch?: string | null; dinner?: string | null; snacks?: string | null }) {
  const tenantId = getTenantIdOrThrow();
  const on = await snacksHere();
  const { snacks, ...meals } = input;
  const data = on && snacks !== undefined ? { ...meals, snacks } : meals;
  const existing = await db.messMenu.findFirst({ where: { dayOfWeek } });
  const row = existing ? await db.messMenu.update({ where: { id: existing.id }, data }) : await db.messMenu.create({ data: { tenantId, dayOfWeek, ...data } });
  return forMenu(row, on);
}

/**
 * The week from a sheet, all or nothing (TEPL, 4 Nov 2026): each day given
 * replaces that day's three meals; a day left out stays as it was. Snacks are
 * replaced only when the sheet had a column for them.
 */
export async function importMenu(days: { dayOfWeek: number; breakfast: string | null; lunch: string | null; dinner: string | null; snacks?: string | null }[]) {
  const tenantId = getTenantIdOrThrow();
  await db.$transaction(
    days.map(({ dayOfWeek, breakfast, lunch, dinner, snacks }) =>
      db.messMenu.upsert({ where: { tenantId_dayOfWeek: { tenantId, dayOfWeek } }, create: { tenantId, dayOfWeek, breakfast, lunch, dinner, snacks }, update: { breakfast, lunch, dinner, snacks } }),
    ),
  );
  return getMenu();
}

// ── Settings (monthly mess fee) ─────────────────────────────────────────────
export async function getSettings() {
  const tenantId = getTenantIdOrThrow();
  const existing = await db.tenantSettings.findFirst({});
  if (existing) return existing;
  return db.tenantSettings.create({ data: { tenantId, messMonthlyFee: 0 } });
}

/** The fee, the mode, and the per-day rate — whichever the caller supplied. */
export async function setMessSettings(input: {
  messMonthlyFee?: number;
  messBillingMode?: MessBillingMode;
  messDailyRate?: number;
}) {
  const tenantId = getTenantIdOrThrow();
  const existing = await db.tenantSettings.findFirst({});
  if (existing) return db.tenantSettings.update({ where: { id: existing.id }, data: input });
  return db.tenantSettings.create({ data: { tenantId, ...input } });
}

export async function setMessFee(messMonthlyFee: number) {
  const tenantId = getTenantIdOrThrow();
  const existing = await db.tenantSettings.findFirst({});
  if (existing) return db.tenantSettings.update({ where: { id: existing.id }, data: { messMonthlyFee } });
  return db.tenantSettings.create({ data: { tenantId, messMonthlyFee } });
}

// ── Attendance (student per-day opt in/out) ─────────────────────────────────
async function myProfile(userId: string) {
  const profile = await db.studentProfile.findFirst({ where: { userId } });
  if (!profile) throw new NotFoundError('No student profile for this account');
  return profile;
}

/**
 * Mark a student on or off the mess for a day. Admin-only by design: students
 * marking themselves off retrospectively, after the bill lands, is the single
 * biggest source of mess-billing arguments.
 */
export async function setStudentAttendance(studentProfileId: string, dateStr: string, present: boolean) {
  const student = await db.studentProfile.findFirst({ where: { id: studentProfileId } });
  if (!student) throw new NotFoundError('Student not found');
  const date = new Date(`${dateStr}T00:00:00.000Z`);
  const existing = await db.messAttendance.findFirst({ where: { studentProfileId, date } });
  if (existing) return db.messAttendance.update({ where: { id: existing.id }, data: { present } });
  return db.messAttendance.create({ data: { tenantId: student.tenantId, studentProfileId, date, present } });
}

/** Everyone marked off on a given date — what the kitchen needs for headcount. */
export async function getAbsencesForMonth(period: string) {
  const [y, m] = period.split('-').map(Number);
  const start = new Date(Date.UTC(y, m - 1, 1));
  const end = new Date(Date.UTC(y, m, 0));
  const rows = await db.messAttendance.findMany({
    where: { date: { gte: start, lte: end }, present: false },
    include: { student: { include: { user: { select: { id: true, name: true } } } } },
    orderBy: { date: 'asc' },
  });
  return rows.map((r) => ({
    id: r.id,
    date: r.date.toISOString().slice(0, 10),
    studentProfileId: r.studentProfileId,
    name: r.student.user.name,
  }));
}

export async function setMyAttendance(userId: string, dateStr: string, present: boolean) {
  const tenantId = getTenantIdOrThrow();
  const profile = await myProfile(userId);
  const date = new Date(`${dateStr}T00:00:00.000Z`);
  const existing = await db.messAttendance.findFirst({ where: { studentProfileId: profile.id, date } });
  if (existing) return db.messAttendance.update({ where: { id: existing.id }, data: { present } });
  return db.messAttendance.create({ data: { tenantId, studentProfileId: profile.id, date, present } });
}

export async function getMyAttendance(userId: string, period: string) {
  const profile = await myProfile(userId);
  const { start, end } = monthRange(period);
  const records = await db.messAttendance.findMany({
    where: { studentProfileId: profile.id, date: { gte: start, lte: end } },
    orderBy: { date: 'asc' },
  });
  return records.map((r) => ({ date: r.date.toISOString().slice(0, 10), present: r.present }));
}
