import { prismaUnscoped, db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { audienceMembers, eventWhereFor } from '../communication/audience';
import { inBackground, pushTo } from '../notifications/notifications.service';
import { paginated, type Pagination } from '../../lib/pagination';
import type { Prisma } from '@prisma/client';

/**
 * Events (Sprint 5, TEPL): the hostel's calendar — a cricket match, Pongal,
 * a yoga morning, a safety training. Employees see the ones meant for them
 * (block, floor, shift, department, as on a notice), register from the app,
 * are marked present on the day, and rate it afterwards. Publishing tells
 * them; two hours before, those registered are reminded.
 */

export const CATEGORIES = ['SPORTS', 'CULTURAL', 'FESTIVAL', 'WELLNESS', 'TRAINING', 'OTHER'] as const;

export interface EventInput {
  title: string;
  description?: string | null;
  category?: string;
  venue?: string | null;
  propertyId?: string | null;
  startsAt: Date;
  endsAt: Date;
  capacity?: number | null;
  registrationClosesAt?: Date | null;
  floors?: number[];
  shiftIds?: string[];
  departmentIds?: string[];
}

function checkTimes(e: { startsAt: Date; endsAt: Date; registrationClosesAt?: Date | null }) {
  if (e.endsAt <= e.startsAt) throw new BadRequestError('The event must end after it starts');
  if (e.registrationClosesAt && e.registrationClosesAt > e.endsAt) throw new BadRequestError('Registration must close before the event ends');
}

/** Counts per event: registered (not cancelled), present, rated and the average rating. */
async function tally(ids: string[]) {
  const rows = await db.eventRegistration.findMany({ where: { eventId: { in: ids }, status: 'REGISTERED' }, select: { eventId: true, attendedAt: true, rating: true } });
  const t = new Map<string, { registered: number; attended: number; ratings: number; avgRating: number | null }>();
  for (const id of ids) {
    const mine = rows.filter((r) => r.eventId === id);
    const rated = mine.filter((r) => r.rating !== null);
    t.set(id, { registered: mine.length, attended: mine.filter((r) => r.attendedAt).length, ratings: rated.length, avgRating: rated.length ? Math.round((rated.reduce((n, r) => n + r.rating!, 0) / rated.length) * 10) / 10 : null });
  }
  return t;
}

// ── The office ──────────────────────────────────────────────────────────────

type EventFilter = { from?: Date; to?: Date; propertyId?: string; includeCancelled?: boolean };
const eventWhere = (f: EventFilter): Prisma.EventWhereInput => ({
  ...(f.includeCancelled ? {} : { status: 'SCHEDULED' }),
  ...(f.propertyId ? { OR: [{ propertyId: f.propertyId }, { propertyId: null }] } : {}),
  // Events that overlap the range: still running at its start counts.
  ...(f.from ? { endsAt: { gte: f.from } } : {}),
  ...(f.to ? { startsAt: { lt: f.to } } : {}),
});

export async function listEvents(f: EventFilter) {
  const rows = await db.event.findMany({ where: eventWhere(f), orderBy: { startsAt: 'asc' }, take: 500 });
  const t = await tally(rows.map((r) => r.id));
  return rows.map((r) => ({ ...r, ...t.get(r.id)! }));
}

/**
 * Events a page at a time (Sprint L3), soonest first as before; the id breaks
 * ties. `ended` keeps only events that are over, newest first — the Past tab,
 * which used to drop the rest and reverse the list itself.
 */
export async function pageEvents(f: EventFilter & { ended?: boolean }, pagination: Pagination) {
  const base = eventWhere(f);
  const where: Prisma.EventWhereInput = f.ended ? { AND: [base, { endsAt: { lt: new Date() } }] } : base;
  const order = f.ended ? ('desc' as const) : ('asc' as const);
  const [rows, total] = await Promise.all([
    db.event.findMany({ where, orderBy: [{ startsAt: order }, { id: order }], skip: pagination.skip, take: pagination.limit }),
    db.event.count({ where }),
  ]);
  const t = await tally(rows.map((r) => r.id));
  return paginated(rows.map((r) => ({ ...r, ...t.get(r.id)! })), total, pagination);
}

export async function createEvent(input: EventInput, actorId: string) {
  checkTimes(input);
  if (input.propertyId && !(await db.property.findFirst({ where: { id: input.propertyId }, select: { id: true } }))) throw new BadRequestError('Unknown block');
  const tenantId = getTenantIdOrThrow();
  const e = await db.event.create({ data: { ...input, floors: input.floors ?? [], shiftIds: input.shiftIds ?? [], departmentIds: input.departmentIds ?? [], tenantId, createdById: actorId } });
  inBackground('push: event', async () => {
    const members = await audienceMembers(tenantId, e);
    const when = e.startsAt.toLocaleString('en-IN', { weekday: 'short', day: 'numeric', month: 'short', hour: 'numeric', minute: '2-digit', timeZone: 'Asia/Kolkata' });
    await pushTo(tenantId, 'EVENT_PUBLISHED', e.id, members.map((m) => m.userId), { title: `New event: ${e.title}`, body: `${when}${e.venue ? ` · ${e.venue}` : ''}. Register in the app.`, data: { eventId: e.id } });
  });
  return e;
}

export async function updateEvent(id: string, input: Partial<EventInput> & { status?: 'SCHEDULED' | 'CANCELLED' }) {
  const e = await db.event.findFirst({ where: { id } });
  if (!e) throw new NotFoundError('Event not found');
  checkTimes({ startsAt: input.startsAt ?? e.startsAt, endsAt: input.endsAt ?? e.endsAt, registrationClosesAt: input.registrationClosesAt !== undefined ? input.registrationClosesAt : e.registrationClosesAt });
  const updated = await db.event.update({ where: { id }, data: input });
  if (input.status === 'CANCELLED' && e.status !== 'CANCELLED') {
    const tenantId = getTenantIdOrThrow();
    inBackground('push: event cancelled', async () => {
      const regs = await db.eventRegistration.findMany({ where: { eventId: id, status: 'REGISTERED' }, select: { studentProfileId: true } });
      const users = await db.studentProfile.findMany({ where: { id: { in: regs.map((r) => r.studentProfileId) } }, select: { userId: true } });
      await pushTo(tenantId, 'EVENT_PUBLISHED', `${id}:cancelled`, users.map((u) => u.userId), { title: `Cancelled: ${e.title}`, body: 'This event will not take place.', data: { eventId: id } });
    });
  }
  return updated;
}

/**
 * The attendance sheet a page at a time (Sprint L3), in the order people
 * registered, with the event and its whole tally on every page. `q` finds
 * people by name, employee ID, phone or room across the sheet; `status` keeps
 * the registered or the cancelled.
 */
export async function pageRoster(id: string, q: string | undefined, pagination: Pagination, status?: 'REGISTERED' | 'CANCELLED') {
  const e = await db.event.findFirst({ where: { id } });
  if (!e) throw new NotFoundError('Event not found');
  let where: Prisma.EventRegistrationWhereInput = { eventId: id, ...(status ? { status } : {}) };
  if (q) {
    const contains = { contains: q, mode: 'insensitive' as const };
    const found = await db.studentProfile.findMany({ where: { OR: [{ user: { name: contains } }, { employeeCode: contains }, { user: { phone: contains } }, { bed: { room: { number: contains } } }] }, select: { id: true }, take: 500 });
    where = { ...where, studentProfileId: { in: found.map((p) => p.id) } };
  }
  const [regs, total] = await Promise.all([
    db.eventRegistration.findMany({ where, orderBy: [{ registeredAt: 'asc' }, { id: 'asc' }], skip: pagination.skip, take: pagination.limit }),
    db.eventRegistration.count({ where }),
  ]);
  return { event: { ...e, ...(await tally([id])).get(id)! }, ...paginated(await sheetRows(regs), total, pagination) };
}

async function sheetRows<T extends { studentProfileId: string }>(regs: T[]) {
  const people = await db.studentProfile.findMany({
    where: { id: { in: regs.map((r) => r.studentProfileId) } },
    select: { id: true, employeeCode: true, user: { select: { name: true, phone: true } }, bed: { select: { label: true, room: { select: { number: true } } } } },
  });
  const who = new Map(people.map((p) => [p.id, p]));
  return regs.map((r) => {
    const p = who.get(r.studentProfileId);
    return { ...r, name: p?.user.name ?? '—', phone: p?.user.phone ?? null, employeeCode: p?.employeeCode ?? null, room: p?.bed ? `Room ${p.bed.room.number} · Bed ${p.bed.label}` : null };
  });
}

/** Who registered, and who came: the attendance sheet. */
export async function roster(id: string) {
  const e = await db.event.findFirst({ where: { id } });
  if (!e) throw new NotFoundError('Event not found');
  const regs = await db.eventRegistration.findMany({ where: { eventId: id }, orderBy: { registeredAt: 'asc' } });
  return { event: { ...e, ...(await tally([id])).get(id)! }, registrations: await sheetRows(regs) };
}

/** Mark present (or not); a walk-in who never registered is added as they come. */
export async function markAttendance(id: string, studentProfileId: string, present: boolean) {
  const e = await db.event.findFirst({ where: { id }, select: { id: true, startsAt: true, status: true } });
  if (!e) throw new NotFoundError('Event not found');
  if (e.status === 'CANCELLED') throw new ConflictError('This event was cancelled');
  if (e.startsAt.getTime() - Date.now() > 3 * 3_600_000) throw new ConflictError('Attendance opens three hours before it starts');
  if (!(await db.studentProfile.findFirst({ where: { id: studentProfileId }, select: { id: true } }))) throw new NotFoundError('Employee not found');
  return db.eventRegistration.upsert({
    where: { eventId_studentProfileId: { eventId: id, studentProfileId } },
    create: { tenantId: getTenantIdOrThrow(), eventId: id, studentProfileId, attendedAt: present ? new Date() : null },
    update: { status: 'REGISTERED', attendedAt: present ? new Date() : null },
  });
}

/** Feedback after the event: the ratings and comments. */
export async function feedback(id: string) {
  const r = await roster(id);
  const rated = r.registrations.filter((x) => x.rating !== null);
  const dist = [1, 2, 3, 4, 5].map((n) => ({ rating: n, count: rated.filter((x) => x.rating === n).length }));
  return { event: r.event, distribution: dist, comments: rated.filter((x) => x.comment).map((x) => ({ rating: x.rating!, comment: x.comment!, at: x.ratedAt })) };
}

// ── The employee ────────────────────────────────────────────────────────────

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

/** The events meant for this employee: upcoming, and the last month's (to rate). */
export async function myEvents(userId: string) {
  const tenantId = getTenantIdOrThrow();
  const p = await profileOf(userId);
  // The notice audience rule, applied to events: same fields, same meaning.
  const rows = await db.event.findMany({
    where: { AND: [await eventWhereFor(tenantId, userId), { endsAt: { gte: new Date(Date.now() - 30 * 86_400_000) } }] },
    orderBy: { startsAt: 'asc' },
    take: 200,
  });
  const [t, mine] = await Promise.all([tally(rows.map((r) => r.id)), db.eventRegistration.findMany({ where: { studentProfileId: p.id, eventId: { in: rows.map((r) => r.id) } } })]);
  const reg = new Map(mine.map((m) => [m.eventId, m]));
  return rows.map((e) => {
    const r = reg.get(e.id);
    const counts = t.get(e.id)!;
    return { ...e, registered: counts.registered, avgRating: counts.avgRating, mine: r && r.status === 'REGISTERED' ? { registeredAt: r.registeredAt, attendedAt: r.attendedAt, rating: r.rating, comment: r.comment } : null, full: !!e.capacity && counts.registered >= e.capacity };
  });
}

async function eventFor(userId: string, id: string) {
  const e = await db.event.findFirst({ where: { AND: [{ id }, await eventWhereFor(getTenantIdOrThrow(), userId)] } });
  if (!e) throw new NotFoundError('Event not found');
  return e;
}

export async function register(userId: string, id: string) {
  const p = await profileOf(userId);
  const e = await eventFor(userId, id);
  if (e.status === 'CANCELLED') throw new ConflictError('This event was cancelled');
  const closes = e.registrationClosesAt ?? e.startsAt;
  if (Date.now() > closes.getTime()) throw new ConflictError('Registration has closed');
  return db.$transaction(async (tx) => {
    if (e.capacity) {
      const taken = await tx.eventRegistration.count({ where: { eventId: id, status: 'REGISTERED', studentProfileId: { not: p.id } } });
      if (taken >= e.capacity) throw new ConflictError('This event is full');
    }
    return tx.eventRegistration.upsert({
      where: { eventId_studentProfileId: { eventId: id, studentProfileId: p.id } },
      create: { tenantId: getTenantIdOrThrow(), eventId: id, studentProfileId: p.id },
      update: { status: 'REGISTERED', registeredAt: new Date() },
    });
  });
}

export async function cancelRegistration(userId: string, id: string) {
  const p = await profileOf(userId);
  const e = await eventFor(userId, id);
  if (e.startsAt.getTime() <= Date.now()) throw new ConflictError('The event has started');
  const r = await db.eventRegistration.findFirst({ where: { eventId: id, studentProfileId: p.id, status: 'REGISTERED' } });
  if (!r) throw new NotFoundError('You are not registered');
  return db.eventRegistration.update({ where: { id: r.id }, data: { status: 'CANCELLED' } });
}

/** A rating after it ended, from someone who registered or was marked present. */
export async function rate(userId: string, id: string, rating: number, comment?: string | null) {
  const p = await profileOf(userId);
  const e = await eventFor(userId, id);
  if (e.endsAt.getTime() > Date.now()) throw new ConflictError('Rate it once it is over');
  const r = await db.eventRegistration.findFirst({ where: { eventId: id, studentProfileId: p.id, status: 'REGISTERED' } });
  if (!r) throw new ConflictError('Only those who took part can rate it');
  return db.eventRegistration.update({ where: { id: r.id }, data: { rating, comment: comment ?? null, ratedAt: new Date() } });
}

// ── Reminders ───────────────────────────────────────────────────────────────

/** Hourly: events starting in the next two hours remind those registered, once. */
export async function runEventReminders(now = new Date()) {
  const soon = await prismaUnscoped.event.findMany({ where: { status: 'SCHEDULED', remindedAt: null, startsAt: { gt: now, lte: new Date(now.getTime() + 2 * 3_600_000) } }, take: 200 });
  for (const e of soon) {
    if (!(await tenantHasFeature(e.tenantId, 'events'))) continue;
    await prismaUnscoped.event.update({ where: { id: e.id }, data: { remindedAt: now } });
    const regs = await prismaUnscoped.eventRegistration.findMany({ where: { eventId: e.id, status: 'REGISTERED' }, select: { studentProfileId: true } });
    const users = await prismaUnscoped.studentProfile.findMany({ where: { id: { in: regs.map((r) => r.studentProfileId) } }, select: { userId: true } });
    const at = e.startsAt.toLocaleTimeString('en-IN', { hour: 'numeric', minute: '2-digit', timeZone: 'Asia/Kolkata' });
    await pushTo(e.tenantId, 'EVENT_REMINDER', e.id, users.map((u) => u.userId), { title: `${e.title} at ${at}`, body: e.venue ? `At ${e.venue}. See you there.` : 'See you there.', data: { eventId: e.id } }).catch((err) => console.error('[push] event reminder failed:', err)); // eslint-disable-line no-console
  }
}
