import { PunchType, StudentRequestStatus, StudentRequestType } from '@prisma/client';
import { db, prismaUnscoped } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';

/**
 * The canteen (Sprint 5, TEPL), on top of the mess module: meal windows that
 * split each swipe into breakfast, lunch, snacks or dinner; each employee's
 * diet, and diet menus beside the main one; meals served against those
 * expected, day by day and diet by diet; ratings per meal; and the canteen
 * vendor's swipe feed, which lands in the same place as the mess terminal's.
 */

export const MEALS = ['BREAKFAST', 'LUNCH', 'SNACKS', 'DINNER'] as const;
export type Meal = (typeof MEALS)[number];
export const PREFERENCES = ['VEG', 'NON_VEG', 'EGG', 'JAIN', 'VEGAN'] as const;
export const RESTRICTIONS = ['DIABETIC', 'LOW_SALT', 'LOW_OIL', 'GLUTEN_FREE', 'LACTOSE_FREE', 'NUT_FREE'] as const;

export const DEFAULT_WINDOWS: { meal: Meal; startTime: string; endTime: string }[] = [
  { meal: 'BREAKFAST', startTime: '06:30', endTime: '09:30' },
  { meal: 'LUNCH', startTime: '12:00', endTime: '14:30' },
  { meal: 'SNACKS', startTime: '16:30', endTime: '17:30' },
  { meal: 'DINNER', startTime: '19:00', endTime: '22:30' },
];

const IST_MS = 330 * 60_000;
const DAY = 86_400_000;
const minutesOf = (hhmm: string) => {
  const [h, m] = hhmm.split(':').map(Number);
  return h * 60 + m;
};
const istYmd = (t: number) => new Date(t + IST_MS).toISOString().slice(0, 10);
const istMinutes = (d: Date) => {
  const ist = new Date(d.getTime() + IST_MS);
  return ist.getUTCHours() * 60 + ist.getUTCMinutes();
};
const asDate = (ymd: string) => new Date(`${ymd}T00:00:00.000Z`);

// ── Meal windows ────────────────────────────────────────────────────────────

/** A block's windows: its own, else the account's, else the defaults. Unscoped with an explicit tenant (the ingest runs on a device). */
export async function windowsFor(tenantId: string, propertyId?: string | null) {
  const rows = await prismaUnscoped.mealWindow.findMany({ where: { tenantId, OR: [{ propertyId: propertyId ?? null }, { propertyId: null }] } });
  return DEFAULT_WINDOWS.map((d) => {
    const block = propertyId ? rows.find((r) => r.meal === d.meal && r.propertyId === propertyId) : undefined;
    const all = rows.find((r) => r.meal === d.meal && r.propertyId === null);
    const own = block ?? all;
    // Where the times come from: the block's own, every block's, or the defaults.
    const scope: 'BLOCK' | 'ALL' | 'DEFAULT' = block ? 'BLOCK' : all ? 'ALL' : 'DEFAULT';
    return { meal: d.meal, startTime: own?.startTime ?? d.startTime, endTime: own?.endTime ?? d.endTime, custom: !!own, scope };
  });
}

/** Which meal a moment falls in; a swipe a little early or late goes to the nearest meal within an hour. */
export function mealAt(windows: { meal: Meal; startTime: string; endTime: string }[], at: Date): Meal | null {
  const m = istMinutes(at);
  const inside = windows.find((w) => m >= minutesOf(w.startTime) && m <= minutesOf(w.endTime));
  if (inside) return inside.meal;
  let best: { meal: Meal; gap: number } | null = null;
  for (const w of windows) {
    const gap = Math.min(Math.abs(m - minutesOf(w.startTime)), Math.abs(m - minutesOf(w.endTime)));
    if (gap <= 60 && (!best || gap < best.gap)) best = { meal: w.meal, gap };
  }
  return best?.meal ?? null;
}

/** For many swipes at once: each block's windows fetched once. */
export function mealClassifier(tenantId: string) {
  const cache = new Map<string, Promise<Awaited<ReturnType<typeof windowsFor>>>>();
  return async (propertyId: string | null | undefined, at: Date) => {
    const key = propertyId ?? '';
    if (!cache.has(key)) cache.set(key, windowsFor(tenantId, propertyId));
    return mealAt(await cache.get(key)!, at);
  };
}

export async function saveWindows(propertyId: string | null, windows: { meal: Meal; startTime: string; endTime: string }[]) {
  const tenantId = getTenantIdOrThrow();
  for (const w of windows) if (minutesOf(w.endTime) <= minutesOf(w.startTime)) throw new BadRequestError(`${w.meal.toLowerCase()} must end after it starts`);
  const sorted = [...windows].sort((a, b) => minutesOf(a.startTime) - minutesOf(b.startTime));
  for (let i = 1; i < sorted.length; i++) if (minutesOf(sorted[i].startTime) < minutesOf(sorted[i - 1].endTime)) throw new BadRequestError(`${sorted[i - 1].meal.toLowerCase()} and ${sorted[i].meal.toLowerCase()} overlap`);
  if (propertyId && !(await db.property.findFirst({ where: { id: propertyId }, select: { id: true } }))) throw new BadRequestError('Unknown block');
  for (const w of windows) {
    const existing = await db.mealWindow.findFirst({ where: { propertyId, meal: w.meal }, select: { id: true } });
    if (existing) await db.mealWindow.update({ where: { id: existing.id }, data: { startTime: w.startTime, endTime: w.endTime } });
    else await db.mealWindow.create({ data: { tenantId, propertyId, ...w } });
  }
  return windowsFor(tenantId, propertyId);
}

// ── Diets ───────────────────────────────────────────────────────────────────

async function profileOf(userId: string) {
  const p = await db.studentProfile.findFirst({ where: { userId }, select: { id: true, propertyId: true } });
  if (!p) throw new NotFoundError('No employee record for this account');
  return p;
}

export async function myDiet(userId: string) {
  const p = await profileOf(userId);
  return db.dietProfile.findFirst({ where: { studentProfileId: p.id } });
}

export async function saveMyDiet(userId: string, input: { preference: string; restrictions: string[]; allergies?: string | null; note?: string | null }) {
  const p = await profileOf(userId);
  const data = { preference: input.preference, restrictions: [...new Set(input.restrictions)], allergies: input.allergies ?? null, note: input.note ?? null };
  return db.dietProfile.upsert({ where: { studentProfileId: p.id }, create: { tenantId: getTenantIdOrThrow(), studentProfileId: p.id, ...data }, update: data });
}

/** The kitchen's view: how many of each diet, and who has a restriction or allergy. */
export async function dietSummary(propertyId?: string) {
  const people = await db.studentProfile.findMany({
    where: { residencyStatus: { not: 'VACATED' }, bedId: { not: null }, ...(propertyId ? { propertyId } : {}) },
    select: { id: true, employeeCode: true, user: { select: { name: true } }, bed: { select: { label: true, room: { select: { number: true } } } } },
    take: 5000,
  });
  const diets = await db.dietProfile.findMany({ where: { studentProfileId: { in: people.map((p) => p.id) } } });
  const of = new Map(diets.map((d) => [d.studentProfileId, d]));
  const byPreference = Object.fromEntries(PREFERENCES.map((k) => [k, 0])) as Record<string, number>;
  const byRestriction = Object.fromEntries(RESTRICTIONS.map((k) => [k, 0])) as Record<string, number>;
  let notSet = 0;
  for (const p of people) {
    const d = of.get(p.id);
    if (!d) {
      notSet++;
      continue;
    }
    byPreference[d.preference] = (byPreference[d.preference] ?? 0) + 1;
    for (const r of d.restrictions) byRestriction[r] = (byRestriction[r] ?? 0) + 1;
  }
  const special = people
    .filter((p) => {
      const d = of.get(p.id);
      return d && (d.restrictions.length > 0 || d.allergies);
    })
    .map((p) => {
      const d = of.get(p.id)!;
      return { studentProfileId: p.id, name: p.user.name, employeeCode: p.employeeCode, room: p.bed ? `Room ${p.bed.room.number} · Bed ${p.bed.label}` : null, preference: d.preference, restrictions: d.restrictions, allergies: d.allergies, note: d.note };
    });
  return { total: people.length, notSet, byPreference, byRestriction, special };
}

// ── Menus ───────────────────────────────────────────────────────────────────

export function dietMenus() {
  return db.dietMenu.findMany({ orderBy: [{ dayOfWeek: 'asc' }, { meal: 'asc' }, { diet: 'asc' }] });
}

export async function saveDietMenu(input: { dayOfWeek: number; meal: string; diet: string; items: string | null }) {
  const existing = await db.dietMenu.findFirst({ where: { dayOfWeek: input.dayOfWeek, meal: input.meal, diet: input.diet }, select: { id: true } });
  if (!input.items) {
    if (existing) await db.dietMenu.delete({ where: { id: existing.id } });
    return null;
  }
  if (existing) return db.dietMenu.update({ where: { id: existing.id }, data: { items: input.items } });
  return db.dietMenu.create({ data: { tenantId: getTenantIdOrThrow(), dayOfWeek: input.dayOfWeek, meal: input.meal, diet: input.diet, items: input.items } });
}

/** The main menu for a day: the day's own (MessDay), else the weekday's (MessMenu). Snacks come from the weekday's alone. */
async function mainMenu(ymd: string) {
  const [day, week] = await Promise.all([db.messDay.findFirst({ where: { date: asDate(ymd) } }), db.messMenu.findFirst({ where: { dayOfWeek: asDate(ymd).getUTCDay() } })]);
  const pick = (k: 'breakfast' | 'lunch' | 'dinner') => day?.[k] ?? week?.[k] ?? null;
  return { BREAKFAST: pick('breakfast'), LUNCH: pick('lunch'), SNACKS: day?.isHoliday ? null : week?.snacks ?? null, DINNER: pick('dinner'), holiday: !!day?.isHoliday };
}

/** An employee's day: each meal's window and menu (with their diet's, if there is one), whether they ate, and their rating. */
export async function myToday(userId: string, ymd = istYmd(Date.now())) {
  const p = await profileOf(userId);
  const tenantId = getTenantIdOrThrow();
  const [windows, menu, diet, dmenus, swipes, ratings] = await Promise.all([
    windowsFor(tenantId, p.propertyId),
    mainMenu(ymd),
    db.dietProfile.findFirst({ where: { studentProfileId: p.id } }),
    db.dietMenu.findMany({ where: { dayOfWeek: asDate(ymd).getUTCDay() } }),
    db.biometricPunch.findMany({ where: { studentProfileId: p.id, type: PunchType.MESS, punchedAt: { gte: new Date(asDate(ymd).getTime() - IST_MS), lt: new Date(asDate(ymd).getTime() - IST_MS + DAY) } }, select: { punchedAt: true, meal: true } }),
    db.mealRating.findMany({ where: { studentProfileId: p.id, date: asDate(ymd) } }),
  ]);
  const mine = diet ? [diet.preference, ...diet.restrictions] : [];
  return {
    date: ymd,
    holiday: menu.holiday,
    diet,
    meals: windows.map((w) => {
      const ate = swipes.find((s) => (s.meal ?? mealAt(windows, s.punchedAt)) === w.meal);
      const r = ratings.find((x) => x.meal === w.meal);
      return {
        meal: w.meal,
        startTime: w.startTime,
        endTime: w.endTime,
        items: menu[w.meal],
        dietItems: dmenus.filter((d) => d.meal === w.meal && mine.includes(d.diet)).map((d) => ({ diet: d.diet, items: d.items })),
        ateAt: ate?.punchedAt ?? null,
        rating: r ? { rating: r.rating, comment: r.comment } : null,
      };
    }),
  };
}

// ── Ratings ─────────────────────────────────────────────────────────────────

/** A rating of today's or yesterday's meal, once it has begun. */
export async function rateMeal(userId: string, input: { date: string; meal: string; rating: number; comment?: string | null }) {
  const p = await profileOf(userId);
  const today = istYmd(Date.now());
  if (input.date !== today && input.date !== istYmd(Date.now() - DAY)) throw new BadRequestError('Rate today’s or yesterday’s meals');
  if (input.date === today) {
    const w = (await windowsFor(getTenantIdOrThrow(), p.propertyId)).find((x) => x.meal === input.meal);
    if (w && istMinutes(new Date()) < minutesOf(w.startTime)) throw new ConflictError('That meal has not been served yet');
  }
  const data = { rating: input.rating, comment: input.comment ?? null };
  return db.mealRating.upsert({
    where: { studentProfileId_date_meal: { studentProfileId: p.id, date: asDate(input.date), meal: input.meal } },
    create: { tenantId: getTenantIdOrThrow(), studentProfileId: p.id, date: asDate(input.date), meal: input.meal, ...data },
    update: data,
  });
}

/** The `days` up to `to` (default today): averages per meal and day, low ratings, comments. */
export async function ratingSummary(days: number, propertyId?: string, to = istYmd(Date.now())) {
  const since = new Date(asDate(to).getTime() - (days - 1) * DAY);
  const rows = await db.mealRating.findMany({ where: { date: { gte: since, lte: asDate(to) } }, orderBy: { createdAt: 'desc' }, take: 20000 });
  const scoped = propertyId ? new Set((await db.studentProfile.findMany({ where: { propertyId }, select: { id: true } })).map((p) => p.id)) : null;
  const list = scoped ? rows.filter((r) => scoped.has(r.studentProfileId)) : rows;
  const avg = (xs: number[]) => (xs.length ? Math.round((xs.reduce((a, b) => a + b, 0) / xs.length) * 10) / 10 : null);
  const byMeal = MEALS.map((meal) => {
    const mine = list.filter((r) => r.meal === meal);
    return { meal, ratings: mine.length, avg: avg(mine.map((r) => r.rating)), low: mine.filter((r) => r.rating <= 2).length };
  });
  const byDay = new Map<string, number[]>();
  for (const r of list) {
    const d = r.date.toISOString().slice(0, 10);
    byDay.set(d, [...(byDay.get(d) ?? []), r.rating]);
  }
  return {
    days,
    byMeal,
    trend: [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, xs]) => ({ day, avg: avg(xs), ratings: xs.length })),
    comments: list.filter((r) => r.comment).slice(0, 30).map((r) => ({ date: r.date, meal: r.meal, rating: r.rating, comment: r.comment })),
    /** Rated 1–2 with a comment: what went wrong, apart from the recent comments. */
    lowComments: list.filter((r) => r.rating <= 2 && r.comment).slice(0, 30).map((r) => ({ date: r.date, meal: r.meal, rating: r.rating, comment: r.comment })),
  };
}

// ── Consumption ─────────────────────────────────────────────────────────────

/**
 * Days from..to (India dates, up to 62): per day and meal, how many ate (one
 * per person per meal), how many were expected — on the mess, not opted out
 * for the day, not on leave — and the diets of those who ate.
 */
export async function consumption(from: string, to: string, propertyId?: string) {
  const a = asDate(from);
  const b = asDate(to);
  const span = (b.getTime() - a.getTime()) / DAY;
  if (!(span >= 0) || span > 61) throw new BadRequestError('Up to two months at a time');
  const tenantId = getTenantIdOrThrow();
  const people = await db.studentProfile.findMany({ where: { residencyStatus: { not: 'VACATED' }, ...(propertyId ? { propertyId } : {}) }, select: { id: true, propertyId: true }, take: 5000 });
  const ids = people.map((p) => p.id);
  const propOf = new Map(people.map((p) => [p.id, p.propertyId]));
  const [swipes, subs, optOuts, leaves, diets] = await Promise.all([
    db.biometricPunch.findMany({ where: { studentProfileId: { in: ids }, type: PunchType.MESS, punchedAt: { gte: new Date(a.getTime() - IST_MS), lt: new Date(b.getTime() - IST_MS + DAY) } }, select: { studentProfileId: true, punchedAt: true, meal: true } }),
    db.messSubscription.findMany({ where: { studentProfileId: { in: ids }, startDate: { lte: b }, OR: [{ endDate: null }, { endDate: { gte: a } }] }, select: { studentProfileId: true, startDate: true, endDate: true } }),
    db.messAttendance.findMany({ where: { studentProfileId: { in: ids }, date: { gte: a, lte: b }, present: false }, select: { studentProfileId: true, date: true } }),
    db.studentRequest.findMany({ where: { studentProfileId: { in: ids }, type: StudentRequestType.LEAVE, status: StudentRequestStatus.APPROVED, fromDate: { lte: b }, toDate: { gte: a } }, select: { studentProfileId: true, fromDate: true, toDate: true } }),
    db.dietProfile.findMany({ where: { studentProfileId: { in: ids } }, select: { studentProfileId: true, preference: true, restrictions: true } }),
  ]);
  const restrictionsOf = new Map(diets.map((d) => [d.studentProfileId, d.restrictions]));
  const classify = mealClassifier(tenantId);
  const dietOf = new Map(diets.map((d) => [d.studentProfileId, d.preference]));
  const served = new Map<string, Set<string>>(); // "day|meal" → people
  for (const s of swipes) {
    if (!s.studentProfileId) continue;
    const meal = s.meal ?? (await classify(propOf.get(s.studentProfileId), s.punchedAt));
    if (!meal) continue;
    const key = `${istYmd(s.punchedAt.getTime())}|${meal}`;
    if (!served.has(key)) served.set(key, new Set());
    served.get(key)!.add(s.studentProfileId);
  }
  const days: { day: string; meals: { meal: Meal; served: number; expected: number; byDiet: Record<string, number> }[]; expectedDiets: { byPreference: Record<string, number>; byRestriction: Record<string, number>; notSet: number } }[] = [];
  for (let t = a.getTime(); t <= b.getTime(); t += DAY) {
    const day = new Date(t).toISOString().slice(0, 10);
    const d = new Date(t);
    const expectedIds = ids.filter(
      (id) =>
        subs.some((s) => s.studentProfileId === id && s.startDate <= d && (!s.endDate || s.endDate >= d)) &&
        !optOuts.some((o) => o.studentProfileId === id && o.date.getTime() === t) &&
        !leaves.some((l) => l.studentProfileId === id && l.fromDate && l.toDate && l.fromDate <= d && l.toDate >= d),
    );
    // Those expected, by diet: what the kitchen cooks for.
    const expectedDiets = { byPreference: {} as Record<string, number>, byRestriction: {} as Record<string, number>, notSet: 0 };
    for (const id of expectedIds) {
      const pref = dietOf.get(id);
      if (!pref) expectedDiets.notSet++;
      else expectedDiets.byPreference[pref] = (expectedDiets.byPreference[pref] ?? 0) + 1;
      for (const r of restrictionsOf.get(id) ?? []) expectedDiets.byRestriction[r] = (expectedDiets.byRestriction[r] ?? 0) + 1;
    }
    days.push({
      day,
      expectedDiets,
      meals: MEALS.map((meal) => {
        const ate = [...(served.get(`${day}|${meal}`) ?? [])];
        const byDiet: Record<string, number> = {};
        for (const id of ate) {
          const k = dietOf.get(id) ?? 'NOT_SET';
          byDiet[k] = (byDiet[k] ?? 0) + 1;
        }
        return { meal, served: ate.length, expected: expectedIds.length, byDiet };
      }),
    });
  }
  const totals = MEALS.map((meal) => {
    const all = days.map((d) => d.meals.find((m) => m.meal === meal)!);
    const s = all.reduce((n, m) => n + m.served, 0);
    const e = all.reduce((n, m) => n + m.expected, 0);
    return { meal, served: s, expected: e, rate: e ? Math.round((s / e) * 100) : null };
  });
  return { from, to, days, totals };
}

/** The kitchen's day so far: per meal, eaten and expected, and the diets of those expected (to cook for). */
export async function today(propertyId?: string) {
  const ymd = istYmd(Date.now());
  const c = await consumption(ymd, ymd, propertyId);
  const diets = await dietSummary(propertyId);
  const expected = c.days[0].expectedDiets;
  // Diets of those expected today (on the mess, not opted out, not on leave); special = with a restriction or allergy.
  return { date: ymd, windows: await windowsFor(getTenantIdOrThrow(), propertyId), meals: c.days[0].meals, diets: { byPreference: expected.byPreference, byRestriction: expected.byRestriction, notSet: expected.notSet, special: diets.special.length } };
}

// ── The vendor's swipe feed ─────────────────────────────────────────────────

/**
 * Swipes from the canteen vendor's own counter system: an id (the card
 * number, terminal id or employee ID), a time, and the meal if they know it.
 * Stored as mess punches, so everything above counts them like the mess
 * terminal's. The same swipe twice is skipped.
 */
export async function ingestVendorSwipes(device: { id: string; tenantId: string }, swipes: { id: string; at: string; meal?: string | null }[]) {
  const keys = [...new Set(swipes.map((s) => s.id))];
  const people = await prismaUnscoped.studentProfile.findMany({
    where: { tenantId: device.tenantId, OR: [{ cardNumber: { in: keys } }, { biometricId: { in: keys } }, { employeeCode: { in: keys } }] },
    select: { id: true, propertyId: true, cardNumber: true, biometricId: true, employeeCode: true },
  });
  const who = new Map<string, { id: string; propertyId: string | null }>();
  for (const p of people) for (const k of [p.employeeCode, p.biometricId, p.cardNumber]) if (k) who.set(k, { id: p.id, propertyId: p.propertyId });
  const classify = mealClassifier(device.tenantId);
  const unmatched = new Set<string>();
  let accepted = 0;
  let duplicates = 0;
  let invalid = 0;
  for (const s of swipes) {
    const at = new Date(s.at);
    if (Number.isNaN(at.getTime())) {
      invalid++;
      continue;
    }
    const p = who.get(s.id);
    if (!p) {
      unmatched.add(s.id);
      continue;
    }
    const meal = s.meal && (MEALS as readonly string[]).includes(s.meal) ? s.meal : await classify(p.propertyId, at);
    try {
      await prismaUnscoped.biometricPunch.create({ data: { tenantId: device.tenantId, deviceId: device.id, biometricId: s.id, studentProfileId: p.id, type: PunchType.MESS, punchedAt: at, meal } });
      accepted++;
      // Eating is being on the mess that day, as with the terminal.
      const date = asDate(istYmd(at.getTime()));
      const existing = await prismaUnscoped.messAttendance.findFirst({ where: { studentProfileId: p.id, date } });
      if (!existing) await prismaUnscoped.messAttendance.create({ data: { tenantId: device.tenantId, studentProfileId: p.id, date, present: true } });
      else if (!existing.present) await prismaUnscoped.messAttendance.update({ where: { id: existing.id }, data: { present: true } });
    } catch (e) {
      if ((e as { code?: string }).code === 'P2002') duplicates++;
      else throw e;
    }
  }
  await prismaUnscoped.biometricDevice.update({ where: { id: device.id }, data: { lastSeenAt: new Date() } });
  return { received: swipes.length, accepted, duplicates, invalid, unmatched: [...unmatched].slice(0, 50) };
}
