import { db, prismaUnscoped } from '../../lib/prisma';
import { inBackground, notifyWorkOrderAssigned } from '../notifications/notifications.service';

/**
 * ZoTag asset tags (Sprint 5 connector, TEPL). Each tagged item in a room's
 * register carries its tag number (RoomAsset.tag). The tag system reports
 * reads: which tag, when, in which room (or by which reader), and the tag's
 * own alarm when it has one. A read keeps the item's "last seen"; a read in
 * another room marks it misplaced; a MISSING or TAMPER alarm marks the item
 * and raises a work order, as a room audit would. Room audits in the app
 * remain the fallback until TEPL's ZoTag API is connected.
 */

export interface TagRead {
  tag: string;
  at: string;
  /** Room number, as on the register (or the reader's name for that room). */
  room?: string | null;
  status?: 'OK' | 'MISSING' | 'TAMPER' | null;
}

export async function ingestTagReads(device: { id: string; tenantId: string }, reads: TagRead[]) {
  const tenantId = device.tenantId;
  const tags = [...new Set(reads.map((r) => r.tag))];
  const assets = await prismaUnscoped.roomAsset.findMany({ where: { tenantId, tag: { in: tags } }, select: { id: true, tag: true, name: true, roomId: true, propertyId: true, status: true, lastSeenAt: true } });
  const byTag = new Map(assets.map((a) => [a.tag!, a]));
  const roomNumbers = [...new Set(reads.map((r) => r.room).filter((x): x is string => !!x))];
  const rooms = roomNumbers.length ? await prismaUnscoped.room.findMany({ where: { tenantId, number: { in: roomNumbers }, archivedAt: null }, select: { id: true, number: true, propertyId: true } }) : [];
  const unknown = new Set<string>();
  let matched = 0;
  let misplaced = 0;
  let raised = 0;
  let invalid = 0;
  for (const r of [...reads].sort((x, y) => Date.parse(x.at) - Date.parse(y.at))) {
    const at = new Date(r.at);
    if (Number.isNaN(at.getTime())) {
      invalid++;
      continue;
    }
    const a = byTag.get(r.tag);
    if (!a) {
      unknown.add(r.tag);
      continue;
    }
    matched++;
    const seenIn = r.room ? rooms.find((x) => x.number === r.room && x.propertyId === a.propertyId) ?? rooms.find((x) => x.number === r.room) : null;
    if (!a.lastSeenAt || at > a.lastSeenAt) {
      await prismaUnscoped.roomAsset.update({ where: { id: a.id }, data: { lastSeenAt: at, ...(seenIn ? { lastSeenRoomId: seenIn.id } : {}) } });
      a.lastSeenAt = at;
    }
    if (seenIn && seenIn.id !== a.roomId) misplaced++;
    if (r.status === 'MISSING' || r.status === 'TAMPER') {
      const next = r.status === 'MISSING' ? 'MISSING' : 'NEEDS_REPAIR';
      if (a.status !== next) {
        await prismaUnscoped.roomAsset.update({ where: { id: a.id }, data: { status: next, note: r.status === 'TAMPER' ? 'Tag tamper alarm' : 'Tag reported missing' } });
        a.status = next;
        const open = await prismaUnscoped.workOrder.findFirst({ where: { tenantId, assetId: a.id, status: { in: ['OPEN', 'IN_PROGRESS'] } }, select: { id: true } });
        if (!open) {
          const room = await prismaUnscoped.room.findUnique({ where: { id: a.roomId }, select: { number: true } });
          const wo = await prismaUnscoped.workOrder.create({
            data: { tenantId, propertyId: a.propertyId, roomId: a.roomId, assetId: a.id, title: `${a.name} ${r.status === 'MISSING' ? 'missing' : 'tag tampered'} — room ${room?.number ?? ''}`.trim(), description: `Reported by the asset-tag system (tag ${r.tag}).`, source: 'TAG', priority: 'HIGH', createdById: device.id },
          });
          raised++;
          if (wo.assigneeId) inBackground('push: work order', () => notifyWorkOrderAssigned(tenantId, wo.id));
        }
      }
    }
  }
  await prismaUnscoped.biometricDevice.update({ where: { id: device.id }, data: { lastSeenAt: new Date() } });
  return { received: reads.length, matched, misplaced, workOrdersRaised: raised, invalid, unknownTags: [...unknown].slice(0, 50) };
}

/** What the tags say needs looking at: items not read for a while, and items read in another room. */
export async function tagExceptions(propertyId: string | undefined, quietDays = 3) {
  const quietSince = new Date(Date.now() - quietDays * 86_400_000);
  const tagged = await db.roomAsset.findMany({ where: { tag: { not: null }, status: { not: 'DISPOSED' }, ...(propertyId ? { propertyId } : {}) }, select: { id: true, name: true, tag: true, roomId: true, status: true, lastSeenAt: true, lastSeenRoomId: true }, take: 10000 });
  const roomIds = [...new Set(tagged.flatMap((a) => [a.roomId, a.lastSeenRoomId].filter((x): x is string => !!x)))];
  const rooms = new Map((await db.room.findMany({ where: { id: { in: roomIds } }, select: { id: true, number: true } })).map((r) => [r.id, r.number]));
  const shape = (a: (typeof tagged)[number]) => ({ ...a, room: rooms.get(a.roomId) ?? null, seenInRoom: a.lastSeenRoomId ? rooms.get(a.lastSeenRoomId) ?? null : null });
  return {
    tagged: tagged.length,
    quietDays,
    notSeen: tagged.filter((a) => !a.lastSeenAt || a.lastSeenAt < quietSince).map(shape),
    misplaced: tagged.filter((a) => a.lastSeenRoomId && a.lastSeenRoomId !== a.roomId).map(shape),
  };
}
