import { Prisma } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';

/**
 * Who a notice or a broadcast is for (Sprint 4, TEPL): everyone living
 * here, narrowed by block, floor, shift or department. Each part that is set
 * narrows; one left empty does not. A shift counts an employee whose usual
 * shift it is, or whose roster puts them on it today.
 *
 * Unscoped with an explicit tenant id: the notifier runs outside a request.
 */

export interface Audience {
  propertyId?: string | null;
  floors?: number[];
  shiftIds?: string[];
  departmentIds?: string[];
}

const IST_MS = 330 * 60_000;
const todayIst = () => new Date(`${new Date(Date.now() + IST_MS).toISOString().slice(0, 10)}T00:00:00.000Z`);

export const isTargeted = (a: Audience) => !!a.propertyId || !!a.floors?.length || !!a.shiftIds?.length || !!a.departmentIds?.length;
export const noticeIsTargeted = (n: { propertyId: string | null; floors: number[]; shiftIds: string[]; departmentIds: string[] }) => isTargeted(n);

/** The employees (and residents) an audience covers: their profile, account and contact. */
export function audienceWhere(tenantId: string, a: Audience): Prisma.StudentProfileWhereInput {
  return {
    tenantId,
    residencyStatus: { not: 'VACATED' },
    user: { deactivatedAt: null },
    ...(a.propertyId ? { propertyId: a.propertyId } : {}),
    ...(a.floors?.length ? { bed: { room: { floor: { in: a.floors } } } } : {}),
    ...(a.departmentIds?.length ? { departmentId: { in: a.departmentIds } } : {}),
    ...(a.shiftIds?.length ? { OR: [{ defaultShiftId: { in: a.shiftIds } }, { rosterEntries: { some: { date: todayIst(), shiftId: { in: a.shiftIds } } } }] } : {}),
  };
}

/**
 * How many people each notice is for, from one grouped query instead of a
 * count per notice (a board of must-acknowledge notices ran one count each).
 *
 * The query counts the tenant's residents — not moved out, an active account,
 * as `audienceWhere` — grouped by what an audience can narrow on: block,
 * floor, department, usual shift and today's rostered shift. A tenant has a
 * handful of such groups however many residents it has, and each notice's
 * total is the sum of the groups its audience matches, by the same rule as
 * `audienceWhere`. Raw SQL skips the scoped client, so the tenant id is
 * explicit; another tenant's residents are never counted.
 */
export async function audienceCountsForNotices<T extends { id: string } & Audience>(tenantId: string, notices: T[]): Promise<Map<string, number>> {
  if (notices.length === 0) return new Map();
  const groups = await prismaUnscoped.$queryRaw<
    { propertyId: string | null; floor: number | null; departmentId: string | null; defaultShiftId: string | null; rosterShiftId: string | null; n: number }[]
  >(Prisma.sql`
    SELECT sp."propertyId", r.floor, sp."departmentId", sp."defaultShiftId", re."shiftId" AS "rosterShiftId", count(*)::int AS n
    FROM "StudentProfile" sp
    JOIN "User" u ON u.id = sp."userId" AND u."deactivatedAt" IS NULL
    LEFT JOIN "Bed" b ON b.id = sp."bedId"
    LEFT JOIN "Room" r ON r.id = b."roomId"
    LEFT JOIN "RosterEntry" re ON re."studentProfileId" = sp.id AND re.date = ${todayIst().toISOString().slice(0, 10)}::date
    WHERE sp."tenantId" = ${tenantId} AND sp."residencyStatus" <> 'VACATED'
    GROUP BY 1, 2, 3, 4, 5
  `);
  const matches = (a: Audience, g: (typeof groups)[number]) =>
    (!a.propertyId || g.propertyId === a.propertyId) &&
    (!a.floors?.length || (g.floor !== null && a.floors.includes(g.floor))) &&
    (!a.departmentIds?.length || (g.departmentId !== null && a.departmentIds.includes(g.departmentId))) &&
    (!a.shiftIds?.length || (g.defaultShiftId !== null && a.shiftIds.includes(g.defaultShiftId)) || (g.rosterShiftId !== null && a.shiftIds.includes(g.rosterShiftId)));
  return new Map(notices.map((n) => [n.id, groups.reduce((total, g) => total + (matches(n, g) ? g.n : 0), 0)]));
}

export async function audienceMembers(tenantId: string, a: Audience) {
  const rows = await prismaUnscoped.studentProfile.findMany({
    where: audienceWhere(tenantId, a),
    select: { id: true, userId: true, user: { select: { name: true, phone: true, email: true } }, bed: { select: { label: true, room: { select: { number: true } } } } },
    orderBy: { user: { name: 'asc' } },
    take: 5000,
  });
  return rows.map((r) => ({ studentProfileId: r.id, userId: r.userId, name: r.user.name, phone: r.user.phone, email: r.user.email, room: r.bed ? `Room ${r.bed.room.number} · Bed ${r.bed.label}` : null }));
}

export async function noticeAudienceUserIds(tenantId: string, a: Audience) {
  return (await audienceMembers(tenantId, a)).map((m) => m.userId);
}

/** What decides which notices and events one resident gets: their block, floor, shifts (usual and today's) and department. */
async function residentFacts(tenantId: string, userId: string) {
  const p = await prismaUnscoped.studentProfile.findFirst({
    where: { tenantId, userId },
    select: { propertyId: true, departmentId: true, defaultShiftId: true, bed: { select: { room: { select: { floor: true } } } }, rosterEntries: { where: { date: todayIst() }, select: { shiftId: true } } },
  });
  return {
    propertyId: p?.propertyId ?? null,
    floor: p?.bed?.room.floor ?? null,
    shifts: [p?.defaultShiftId, ...(p?.rosterEntries.map((r) => r.shiftId) ?? [])].filter((x): x is string => !!x),
    departmentId: p?.departmentId ?? null,
  };
}

type Facts = Awaited<ReturnType<typeof residentFacts>>;

/** Untargeted ones, and those whose every set part matches the resident. Same shape for notices and events. */
const matching = (f: Facts) => [
  { OR: [{ propertyId: null }, ...(f.propertyId ? [{ propertyId: f.propertyId }] : [])] },
  { OR: [{ floors: { isEmpty: true } }, ...(f.floor !== null ? [{ floors: { has: f.floor } }] : [])] },
  { OR: [{ shiftIds: { isEmpty: true } }, ...(f.shifts.length ? [{ shiftIds: { hasSome: f.shifts } }] : [])] },
  { OR: [{ departmentIds: { isEmpty: true } }, ...(f.departmentId ? [{ departmentIds: { has: f.departmentId } }] : [])] },
];

/** The notices one resident may read. */
export async function noticeWhereFor(tenantId: string, userId: string): Promise<Prisma.NoticeWhereInput> {
  return { AND: matching(await residentFacts(tenantId, userId)) };
}

/** The events one resident is offered (Sprint 5): the same rule as notices. */
export async function eventWhereFor(tenantId: string, userId: string): Promise<Prisma.EventWhereInput> {
  return { AND: matching(await residentFacts(tenantId, userId)) };
}
