import {
  BadRequestException,
  ForbiddenException,
  Injectable,
  NotFoundException,
  PayloadTooLargeException,
  UnsupportedMediaTypeException,
} from '@nestjs/common';
import type { Attachment, AttachmentOwnerType, ReferenceDomain } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import type { AuthUser } from '../trpc/auth-user';
import { StorageService } from './storage.service';

const MAX_BYTES = 10 * 1024 * 1024; // 10 MB
const ALLOWED_MIME = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/heic', 'application/pdf']);

/** Marks an attachment the office added for itself. Set when staff attach proof
 *  to a refused payment; nothing a tenant uploads ever carries it. */
export const STAFF_EVIDENCE = 'STAFF_EVIDENCE';

/** The owners whose files are classified, each by its own list the office keeps
 *  on the Option Lists screen: a building's purchase paperwork, and the repair
 *  slips and receipts behind a repair. A file on either must name one. */
const DOCUMENT_TYPES: Partial<Record<AttachmentOwnerType, ReferenceDomain>> = {
  PROPERTY: 'PROPERTY_DOCUMENT_TYPE',
  MAINTENANCE_REQUEST: 'MAINTENANCE_DOCUMENT_TYPE',
};

@Injectable()
export class AttachmentService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly storage: StorageService,
  ) {}

  /** Authorises that `user` may write-to / read-from the owner in `org`.
   * Tenants are confined to their OWN receipts/requests; staff need the matching
   * permission. This is the access gate the legacy public-path storage lacked. */
  private async assertOwnerAccess(
    user: AuthUser,
    organizationId: string,
    ownerType: AttachmentOwnerType,
    ownerId: string,
    mode: 'read' | 'write',
  ): Promise<void> {
    if (ownerType === 'RECEIPT') {
      const r = await this.prisma.receipt.findFirst({ where: { id: ownerId, organizationId }, select: { tenantId: true } });
      if (!r) throw new NotFoundException('Receipt not found');
      if (user.tenantId) {
        if (r.tenantId !== user.tenantId) throw new ForbiddenException('Not your receipt');
      } else if (!user.permissions.includes(mode === 'write' ? 'receipt.update' : 'receipt.read')) {
        throw new ForbiddenException('Missing permission');
      }
      return;
    }
    if (ownerType === 'MAINTENANCE_REQUEST') {
      const m = await this.prisma.maintenanceRequest.findFirst({ where: { id: ownerId, organizationId }, select: { tenantId: true } });
      if (!m) throw new NotFoundException('Maintenance request not found');
      if (user.tenantId) {
        if (m.tenantId !== user.tenantId) throw new ForbiddenException('Not your request');
      } else if (!user.permissions.includes(mode === 'write' ? 'maintenance.update' : 'maintenance.read')) {
        throw new ForbiddenException('Missing permission');
      }
      return;
    }
    if (ownerType === 'LEASE') {
      const l = await this.prisma.lease.findFirst({ where: { id: ownerId, organizationId }, select: { tenantId: true } });
      if (!l) throw new NotFoundException('Lease not found');
      if (user.tenantId) {
        // A tenant may view their own lease's documents, but not upload/delete.
        if (l.tenantId !== user.tenantId) throw new ForbiddenException('Not your lease');
        if (mode === 'write') throw new ForbiddenException('Missing permission');
      } else if (!user.permissions.includes(mode === 'write' ? 'lease.update' : 'lease.read')) {
        throw new ForbiddenException('Missing permission');
      }
      return;
    }
    if (ownerType === 'INVOICE' || ownerType === 'INVOICE_LINE') {
      // Evidence behind a charge (a repair bill, a receipt). Tenants may read it
      // on their own issued notes — it is printed on the debit note anyway — but
      // only staff attach it.
      const invoice =
        ownerType === 'INVOICE'
          ? await this.prisma.invoice.findFirst({ where: { id: ownerId, organizationId }, select: { status: true, lease: { select: { tenantId: true } } } })
          : await this.prisma.invoiceLine
              .findFirst({ where: { id: ownerId, invoice: { organizationId } }, select: { invoice: { select: { status: true, lease: { select: { tenantId: true } } } } } })
              .then((l) => l?.invoice ?? null);
      if (!invoice) throw new NotFoundException('Debit note not found');
      if (user.tenantId) {
        if (invoice.lease.tenantId !== user.tenantId) throw new ForbiddenException('Not your debit note');
        if (mode === 'write') throw new ForbiddenException('Missing permission');
        if (['DRAFT', 'PENDING_APPROVAL', 'APPROVED'].includes(invoice.status)) throw new NotFoundException('Debit note not found');
      } else if (!user.permissions.includes(mode === 'write' ? 'invoice.update' : 'invoice.read')) {
        throw new ForbiddenException('Missing permission');
      }
      return;
    }
    if (ownerType === 'PROPERTY_NOTICE') {
      // The scanned letter behind a notice-log entry. Back-office correspondence
      // about a building: a tenant has no branch here at all, not even for a
      // letter addressed to their own tenancy, because the entry is the office's
      // own record of what it sent and its remark is written for the office.
      const n = await this.prisma.propertyNotice.findFirst({ where: { id: ownerId, organizationId }, select: { id: true } });
      if (!n) throw new NotFoundException('Notice not found');
      if (user.tenantId) throw new ForbiddenException('Missing permission');
      if (!user.permissions.includes(mode === 'write' ? 'notice.update' : 'notice.read')) {
        throw new ForbiddenException('Missing permission');
      }
      return;
    }
    if (ownerType === 'PROPERTY') {
      // The building's own paperwork — the assignment, the title deeds, the
      // mortgage deed. The office's records of what the company owns, with no
      // tenant side to them at all, so the tenant branch comes FIRST: there is
      // nothing here to look up on a tenant's behalf, and refusing before the
      // lookup also stops a tenant learning which property ids exist.
      if (user.tenantId) throw new ForbiddenException('Missing permission');
      const p = await this.prisma.property.findFirst({ where: { id: ownerId, organizationId }, select: { id: true } });
      if (!p) throw new NotFoundException('Property not found');
      if (!user.permissions.includes(mode === 'write' ? 'property.update' : 'property.read')) {
        throw new ForbiddenException('Missing permission');
      }
      return;
    }
    if (ownerType === 'METER_READING') {
      const r = await this.prisma.meterReading.findFirst({
        // Scoped through a covered unit, the same way metering.router reaches a
        // reading — the other five branches are org-scoped and this one was not.
        where: { id: ownerId, meter: { units: { some: { unit: { property: { organizationId } } } } } },
        select: { id: true, status: true, submittedByUserId: true },
      });
      if (!r) throw new NotFoundException('Meter reading not found');
      if (user.tenantId) {
        // A tenant reads the dial in their own flat, so they attach the photo
        // that proves the number. Only to their own declaration, and only while
        // it is still waiting to be checked — once confirmed the evidence is
        // fixed. Other readings stay out of reach; their dial photos reach a
        // tenant only as evidence pages on their own debit note.
        if (r.submittedByUserId !== user.id || r.status !== 'PENDING') throw new ForbiddenException('Missing permission');
        return;
      }
      if (!user.permissions.includes(mode === 'write' ? 'meter-reading.update' : 'meter-reading.read')) {
        throw new ForbiddenException('Missing permission');
      }
      return;
    }
    throw new BadRequestException('Unknown attachment owner type');
  }

  /** Resolves the document type a file is filed under, for the owners whose
   * files are classified. Reference values are one table serving many lists, so
   * an id proves nothing on its own: it is checked against THIS org and THIS
   * owner's list, the same way every other field that stores one does. */
  private async resolveDocumentType(organizationId: string, domain: ReferenceDomain, id?: string | null): Promise<string> {
    if (!id) throw new BadRequestException('Choose what kind of document this is');
    const found = await this.prisma.referenceValue.findFirst({
      where: { id, organizationId, domain },
      select: { id: true },
    });
    if (!found) throw new BadRequestException('Document type not found');
    return found.id;
  }

  /** Deletes an attachment (its DB row and the stored file) after authorising the
   * caller against its owner. The row is source of truth, so remove it first. */
  async remove(user: AuthUser, organizationId: string, id: string): Promise<void> {
    const att = await this.prisma.attachment.findFirst({ where: { id, organizationId } });
    if (!att) throw new NotFoundException('Attachment not found');
    await this.assertOwnerAccess(user, organizationId, att.ownerType, att.ownerId, 'write');
    await this.prisma.attachment.delete({ where: { id: att.id } });
    await this.storage.remove(att.storageKey);
  }

  async upload(input: {
    user: AuthUser;
    organizationId: string;
    ownerType: AttachmentOwnerType;
    ownerId: string;
    filename: string;
    mimeType: string;
    buffer: Buffer;
    caption?: string | null;
    /** Owner-defined slot (METER_READING: START | END). A role holds one file:
     * re-uploading replaces what was there, so a reading can't end up with two
     * "start" photos and no way to tell which is current. */
    role?: string | null;
    /** What KIND of document this is — a reference value from the owner's list
     * (DOCUMENT_TYPES). Required on those owners, ignored on every other. Not a
     * `role`: it classifies, it does not supersede, because several title deeds
     * on one building, or receipts behind one repair, are normal. */
    documentTypeId?: string | null;
  }): Promise<Attachment> {
    const ext = this.storage.extForMime(input.mimeType);
    if (!ALLOWED_MIME.has(input.mimeType) || !ext) {
      throw new UnsupportedMediaTypeException(`File type "${input.mimeType}" is not allowed`);
    }
    if (input.buffer.length === 0) throw new BadRequestException('The uploaded file is empty');
    if (input.buffer.length > MAX_BYTES) throw new PayloadTooLargeException('File exceeds the 10MB limit');

    // Authorise BEFORE writing bytes, so a rejected upload leaves nothing on disk.
    await this.assertOwnerAccess(input.user, input.organizationId, input.ownerType, input.ownerId, 'write');
    // Same rule for the classification: resolved before any bytes are written,
    // so a file can never land unfiled or filed under another list's id.
    const typeList = DOCUMENT_TYPES[input.ownerType];
    const documentTypeId = typeList ? await this.resolveDocumentType(input.organizationId, typeList, input.documentTypeId) : null;

    const storageKey = await this.storage.save(input.buffer, ext);
    try {
      const created = await this.prisma.attachment.create({
        data: {
          organizationId: input.organizationId,
          ownerType: input.ownerType,
          ownerId: input.ownerId,
          filename: sanitizeName(input.filename),
          mimeType: input.mimeType,
          sizeBytes: input.buffer.length,
          storageKey,
          caption: input.caption ?? null,
          role: input.role ?? null,
          documentTypeId,
          uploadedByUserId: input.user.id,
        },
      });
      // Created first, then the old one dropped — a failure leaves the previous
      // file in place rather than losing both.
      if (input.role) {
        const superseded = await this.prisma.attachment.findMany({
          where: { organizationId: input.organizationId, ownerType: input.ownerType, ownerId: input.ownerId, role: input.role, id: { not: created.id } },
        });
        for (const old of superseded) {
          await this.prisma.attachment.delete({ where: { id: old.id } });
          await this.storage.remove(old.storageKey).catch(() => undefined);
        }
      }
      return created;
    } catch (err) {
      // The DB row is the source of truth; if it never lands, don't leave the
      // just-written file orphaned on disk with nothing referencing it.
      await this.storage.remove(storageKey);
      throw err;
    }
  }

  async getForDownload(user: AuthUser, organizationId: string, id: string): Promise<Attachment> {
    const att = await this.prisma.attachment.findFirst({ where: { id, organizationId } });
    if (!att) throw new NotFoundException('Attachment not found');
    await this.assertOwnerAccess(user, organizationId, att.ownerType, att.ownerId, 'read');
    // Owner access is not enough on its own here. A receipt carries the tenant's
    // own payment proof AND whatever the office attached when refusing it — a
    // returned-cheque image, a bank statement screenshot. Those are the office's
    // working papers about the tenant, not documents for them, and a statement
    // can show other people's transactions.
    if (user.tenantId && att.role === STAFF_EVIDENCE) throw new ForbiddenException('Missing permission');
    return att;
  }

  listFor(organizationId: string, ownerType: AttachmentOwnerType, ownerId: string) {
    return this.prisma.attachment.findMany({
      where: { organizationId, ownerType, ownerId },
      orderBy: { createdAt: 'asc' },
    });
  }

  streamKey(key: string) {
    return this.storage.stream(key);
  }
}

/** Keep only safe display characters (word chars, dot, dash, space, CJK). */
function sanitizeName(name: string): string {
  return (name || 'file').replace(/[^\w.\-一-鿿 ]+/g, '_').slice(0, 200);
}
