import { Role, StudentRequestStatus } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ForbiddenError, NotFoundError } from '../../lib/errors';
import type { Permission } from '../../lib/permissions';
import { presignDownload, uploadDirect } from '../uploads/uploads.service';

/**
 * Attachments (Sprint 0, TEPL): photos and documents on a record — a ticket
 * today; incidents, found items, parcels and compliance files as those
 * modules arrive. Each kind of record registers an owner rule saying who may
 * see, add and remove its files. The client names the record; the rule, run
 * here, decides.
 */

export interface Viewer {
  userId: string;
  role: Role;
  perms: Permission[];
}

export interface OwnerRule {
  /** May this person see the record's files (and so the record)? */
  canView(viewer: Viewer, ownerId: string): Promise<boolean>;
  /** May they add one now (the record may be closed to changes)? */
  canAdd(viewer: Viewer, ownerId: string): Promise<boolean>;
  /** May they remove files other people added? Everyone may remove their own. */
  canRemoveAny(viewer: Viewer): boolean;
  /** Hide this uploader's name from this viewer (anonymous records). */
  hideUploader?(viewer: Viewer, ownerId: string, uploaderId: string): Promise<boolean>;
}

const OWNERS = new Map<string, OwnerRule>();

export function registerAttachmentOwner(type: string, rule: OwnerRule) {
  OWNERS.set(type, rule);
}

function ruleFor(type: string): OwnerRule {
  const rule = OWNERS.get(type);
  if (!rule) throw new BadRequestError('Files cannot be attached to that');
  return rule;
}

export const MAX_PER_RECORD = 10;

// ── Requests (tickets) ──────────────────────────────────────────────────────

async function requestFacts(id: string) {
  return db.studentRequest.findFirst({
    where: { id },
    select: { status: true, assigneeId: true, anonymous: true, student: { select: { userId: true } } },
  });
}

registerAttachmentOwner('REQUEST', {
  async canView(viewer, id) {
    const r = await requestFacts(id);
    if (!r) return false;
    if (viewer.role === Role.STUDENT) return r.student.userId === viewer.userId;
    return viewer.perms.includes('MANAGE_STUDENTS') || r.assigneeId === viewer.userId;
  },
  async canAdd(viewer, id) {
    const r = await requestFacts(id);
    if (!r || r.status === StudentRequestStatus.CANCELLED) return false;
    return this.canView(viewer, id);
  },
  canRemoveAny: (viewer) => viewer.perms.includes('MANAGE_STUDENTS'),
  async hideUploader(viewer, id, uploaderId) {
    if (viewer.role === Role.STUDENT) return false;
    const r = await requestFacts(id);
    return !!r?.anonymous && r.student.userId === uploaderId;
  },
});

// ── Sprint 2 (TEPL): incidents, parcels, lost and found ─────────────────────

const manages = (v: Viewer) => v.perms.includes('MANAGE_STUDENTS');
const desk = (v: Viewer) => v.perms.includes('MANAGE_GATE') || manages(v);

// Evidence on an incident is for the hostel office only.
registerAttachmentOwner('INCIDENT', {
  canView: async (v, id) => manages(v) && !!(await db.disciplineIncident.findFirst({ where: { id }, select: { id: true } })),
  canAdd: async (v, id) => manages(v) && !!(await db.disciplineIncident.findFirst({ where: { id }, select: { id: true } })),
  canRemoveAny: manages,
});

// A parcel's photo: the desk, and the employee it is for.
registerAttachmentOwner('PARCEL', {
  async canView(v, id) {
    const p = await db.parcel.findFirst({ where: { id }, select: { student: { select: { userId: true } } } });
    return !!p && (desk(v) || p.student.userId === v.userId);
  },
  canAdd: async (v, id) => desk(v) && !!(await db.parcel.findFirst({ where: { id }, select: { id: true } })),
  canRemoveAny: desk,
});

// A found item's photo is for everyone looking for their things; a lost report's, for the desk and who reported it.
registerAttachmentOwner('LOST_FOUND', {
  async canView(v, id) {
    const i = await db.lostFoundItem.findFirst({ where: { id }, select: { kind: true, reportedById: true } });
    return !!i && (desk(v) || i.kind === 'FOUND' || i.reportedById === v.userId);
  },
  async canAdd(v, id) {
    const i = await db.lostFoundItem.findFirst({ where: { id }, select: { status: true, reportedById: true } });
    return !!i && i.status !== 'CLOSED' && (desk(v) || i.reportedById === v.userId);
  },
  canRemoveAny: desk,
});

// ── Sprint 3 (TEPL): cleaning tasks and work orders ─────────────────────────

const supervises = (v: Viewer) => v.perms.includes('MANAGE_HOUSEKEEPING');
const istDay = () => new Date(Date.now() + 330 * 60_000).toISOString().slice(0, 10);

// A clean's photo: the supervisor, and the housekeeper whose task it is (or who picked it up).
registerAttachmentOwner('CLEANING_TASK', {
  async canView(v, id) {
    const t = await db.cleaningTask.findFirst({ where: { id }, select: { assigneeId: true, doneById: true } });
    return !!t && (supervises(v) || t.assigneeId === v.userId || t.doneById === v.userId || (t.assigneeId === null && v.perms.includes('WORK_TASKS')));
  },
  async canAdd(v, id) {
    const t = await db.cleaningTask.findFirst({ where: { id }, select: { assigneeId: true, dueDate: true } });
    if (!t) return false;
    if (supervises(v)) return true;
    // A housekeeper adds to today's own (or nobody's) tasks, as they tick them.
    return v.perms.includes('WORK_TASKS') && (t.assigneeId === null || t.assigneeId === v.userId) && t.dueDate.toISOString().slice(0, 10) === istDay();
  },
  canRemoveAny: supervises,
});

// A repair's before-and-after: whoever runs rooms, and the person it is handed to.
registerAttachmentOwner('WORK_ORDER', {
  async canView(v, id) {
    const w = await db.workOrder.findFirst({ where: { id }, select: { assigneeId: true } });
    return !!w && (v.perms.includes('MANAGE_ROOMS') || w.assigneeId === v.userId);
  },
  async canAdd(v, id) {
    const w = await db.workOrder.findFirst({ where: { id }, select: { assigneeId: true, status: true } });
    return !!w && w.status !== 'CANCELLED' && (v.perms.includes('MANAGE_ROOMS') || w.assigneeId === v.userId);
  },
  canRemoveAny: (v) => v.perms.includes('MANAGE_ROOMS'),
});

// ── Sprint 6 (TEPL): medical documents (ownerId is the employee's profile) ──

const ohc = (v: Viewer) => v.role !== Role.HOSTEL_ADMIN && v.perms.includes('MANAGE_MEDICAL');

// Fitness certificates and reports: the OHC, and the employee their own. Each OHC look is logged.
registerAttachmentOwner('MEDICAL', {
  async canView(v, id) {
    const p = await db.studentProfile.findFirst({ where: { id }, select: { userId: true } });
    if (!p) return false;
    if (ohc(v)) {
      await db.medicalAccessLog.create({ data: { tenantId: getTenantIdOrThrow(), userId: v.userId, studentProfileId: id, action: 'DOCUMENT' } });
      return true;
    }
    return p.userId === v.userId;
  },
  canAdd: async (v, id) => ohc(v) && !!(await db.studentProfile.findFirst({ where: { id }, select: { id: true } })),
  canRemoveAny: ohc,
});

// ── Sprint 7 (TEPL): compliance documents ───────────────────────────────────

const readsCompliance = (v: Viewer) => v.perms.includes('MANAGE_COMPLIANCE') || v.perms.includes('VIEW_COMPLIANCE');
const keepsCompliance = (v: Viewer) => v.perms.includes('MANAGE_COMPLIANCE');
const logComplianceLook = (v: Viewer, entityType: string, entityId: string) =>
  db.complianceAudit.create({ data: { tenantId: getTenantIdOrThrow(), entityType, entityId, action: 'DOCUMENT_VIEWED', actorId: v.userId } });

// Certificates, licences and register scans: read by whoever reads compliance (each look kept), kept by the desk.
registerAttachmentOwner('COMPLIANCE_ITEM', {
  async canView(v, id) {
    if (!readsCompliance(v) || !(await db.complianceItem.findFirst({ where: { id }, select: { id: true } }))) return false;
    await logComplianceLook(v, 'ITEM', id);
    return true;
  },
  canAdd: async (v, id) => keepsCompliance(v) && !!(await db.complianceItem.findFirst({ where: { id, archivedAt: null }, select: { id: true } })),
  canRemoveAny: keepsCompliance,
});

// An inspection's report.
registerAttachmentOwner('COMPLIANCE_INSPECTION', {
  async canView(v, id) {
    if (!readsCompliance(v) || !(await db.complianceInspection.findFirst({ where: { id }, select: { id: true } }))) return false;
    await logComplianceLook(v, 'INSPECTION', id);
    return true;
  },
  canAdd: async (v, id) => keepsCompliance(v) && !!(await db.complianceInspection.findFirst({ where: { id }, select: { id: true } })),
  canRemoveAny: keepsCompliance,
});

// The proof an action was done: also the person it was given to, while it is open.
registerAttachmentOwner('COMPLIANCE_FINDING', {
  async canView(v, id) {
    const f = await db.complianceFinding.findFirst({ where: { id }, select: { ownerId: true } });
    if (!f || !(readsCompliance(v) || f.ownerId === v.userId)) return false;
    await logComplianceLook(v, 'FINDING', id);
    return true;
  },
  async canAdd(v, id) {
    const f = await db.complianceFinding.findFirst({ where: { id }, select: { ownerId: true, status: true } });
    return !!f && f.status === 'OPEN' && (keepsCompliance(v) || f.ownerId === v.userId);
  },
  canRemoveAny: keepsCompliance,
});

// ── The operations ─────────────────────────────────────────────────────────

export async function listAttachments(viewer: Viewer, ownerType: string, ownerId: string) {
  const rule = ruleFor(ownerType);
  // Not found rather than forbidden: no hint that the record exists.
  if (!(await rule.canView(viewer, ownerId))) throw new NotFoundError('Not found');
  const tenantId = getTenantIdOrThrow();
  const rows = await db.attachment.findMany({
    where: { ownerType, ownerId },
    orderBy: { createdAt: 'asc' },
    include: { uploadedBy: { select: { id: true, name: true } } },
  });
  return Promise.all(
    rows.map(async (a) => {
      const hidden = rule.hideUploader && a.uploadedById ? await rule.hideUploader(viewer, ownerId, a.uploadedById) : false;
      return {
        id: a.id,
        name: a.name,
        contentType: a.contentType,
        size: a.size,
        createdAt: a.createdAt,
        uploadedBy: hidden ? null : a.uploadedBy,
        mine: a.uploadedById === viewer.userId,
        url: await presignDownload(tenantId, a.key).catch(() => null),
      };
    }),
  );
}

export async function addAttachment(viewer: Viewer, input: { ownerType: string; ownerId: string; name: string; contentType: string; body: Buffer }) {
  const rule = ruleFor(input.ownerType);
  if (!(await rule.canView(viewer, input.ownerId))) throw new NotFoundError('Not found');
  if (!(await rule.canAdd(viewer, input.ownerId))) throw new ForbiddenError('Files can no longer be added here');
  const count = await db.attachment.count({ where: { ownerType: input.ownerType, ownerId: input.ownerId } });
  if (count >= MAX_PER_RECORD) throw new BadRequestError(`Up to ${MAX_PER_RECORD} files can be attached`);
  const tenantId = getTenantIdOrThrow();
  const { key } = await uploadDirect({ tenantId, kind: 'ATTACHMENT', contentType: input.contentType, body: input.body });
  const a = await db.attachment.create({
    data: { tenantId, ownerType: input.ownerType, ownerId: input.ownerId, key, name: input.name, contentType: input.contentType, size: input.body.length, uploadedById: viewer.userId },
  });
  return { id: a.id, name: a.name, contentType: a.contentType, size: a.size, createdAt: a.createdAt };
}

export async function removeAttachment(viewer: Viewer, id: string) {
  const a = await db.attachment.findFirst({ where: { id } });
  if (!a) throw new NotFoundError('Not found');
  const rule = ruleFor(a.ownerType);
  if (!(await rule.canView(viewer, a.ownerId))) throw new NotFoundError('Not found');
  if (a.uploadedById !== viewer.userId && !rule.canRemoveAny(viewer)) throw new ForbiddenError('Only the person who added it can remove this file');
  // The S3 object stays (as with replaced photos); the record no longer points at it.
  await db.attachment.delete({ where: { id } });
  return { ok: true };
}
