import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { Prisma, type MaintenanceRequest, type MaintenanceTask } from '@prisma/client';
import { Decimal, toCents } from '@rms/domain';
import { StorageService } from '../attachments/storage.service';
import { PrismaService } from '../prisma/prisma.service';
import { REQUEST_TRANSITIONS, RESPONSIBILITIES, TASK_STATUSES } from './maintenance.constants';
import { hkToday } from '../common/hk-date';

const RM_CODE = 'RM'; // seeded Repairs & Maintenance charge type (GL 6000)

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

  private cost(v: string | number | null | undefined): Decimal | undefined {
    if (v == null || v === '') return undefined;
    const d = toCents(new Decimal(v));
    if (d.lt(0)) throw new BadRequestException('Cost cannot be negative');
    return d;
  }

  /** Staff files (or logs on a tenant's behalf) a maintenance request. */
  async create(input: {
    organizationId: string;
    propertyId: string;
    unitId?: string | null;
    tenantId?: string | null;
    leaseId?: string | null;
    categoryId?: string | null;
    priorityId?: string | null;
    title: string;
    description?: string | null;
    costResponsibility?: string | null;
    tenantSharePercent?: string | null;
    estimatedCost?: string | null;
    reportedByUserId?: string | null;
  }): Promise<MaintenanceRequest> {
    const property = await this.prisma.property.findFirst({
      where: { id: input.propertyId, organizationId: input.organizationId, deletedAt: null },
    });
    if (!property) throw new NotFoundException('Property not found');
    if (input.unitId) {
      const unit = await this.prisma.unit.findFirst({ where: { id: input.unitId, propertyId: input.propertyId } });
      if (!unit) throw new BadRequestException('Unit is not on this property');
    }
    if (input.leaseId) {
      const lease = await this.prisma.lease.findFirst({
        where: { id: input.leaseId, organizationId: input.organizationId },
      });
      if (!lease) throw new BadRequestException('Lease not found');
    }
    if (input.tenantId) {
      const t = await this.prisma.tenant.findFirst({
        where: { id: input.tenantId, organizationId: input.organizationId, deletedAt: null },
      });
      if (!t) throw new BadRequestException('Tenant not found');
    }
    const resp = input.costResponsibility ?? 'LANDLORD';
    if (!RESPONSIBILITIES.includes(resp)) throw new BadRequestException('Invalid cost responsibility');
    const share = new Decimal(input.tenantSharePercent ?? 100);
    if (share.lt(0) || share.gt(100)) throw new BadRequestException('Tenant share must be 0–100');

    return this.prisma.maintenanceRequest.create({
      data: {
        organizationId: input.organizationId,
        propertyId: input.propertyId,
        unitId: input.unitId ?? null,
        tenantId: input.tenantId ?? null,
        leaseId: input.leaseId ?? null,
        categoryId: input.categoryId ?? null,
        priorityId: input.priorityId ?? null,
        title: input.title,
        description: input.description ?? null,
        status: 'OPEN',
        costResponsibility: resp,
        tenantSharePercent: share.toFixed(3),
        estimatedCost: this.cost(input.estimatedCost)?.toFixed(2) ?? null,
        reportedByUserId: input.reportedByUserId ?? null,
      },
    });
  }

  /** Edit mutable fields (not status — that goes through transition()). */
  async update(input: {
    organizationId: string;
    id: string;
    categoryId?: string | null;
    priorityId?: string | null;
    title?: string;
    description?: string | null;
    leaseId?: string | null;
    costResponsibility?: string | null;
    tenantSharePercent?: string | null;
    estimatedCost?: string | null;
    actualCost?: string | null;
  }): Promise<MaintenanceRequest> {
    const existing = await this.prisma.maintenanceRequest.findFirst({
      where: { id: input.id, organizationId: input.organizationId },
    });
    if (!existing) throw new NotFoundException('Maintenance request not found');
    if (input.costResponsibility != null && !RESPONSIBILITIES.includes(input.costResponsibility)) {
      throw new BadRequestException('Invalid cost responsibility');
    }
    // Once charged, the cost figures are frozen — they backed an issued/issuable
    // recovery invoice and must not silently diverge from it.
    const changingCost =
      input.actualCost !== undefined || input.costResponsibility != null || input.tenantSharePercent != null;
    if (existing.chargedInvoiceId && changingCost) {
      throw new BadRequestException('Cost fields are locked once the request has been charged to the tenant');
    }
    if (input.leaseId) {
      const lease = await this.prisma.lease.findFirst({
        where: { id: input.leaseId, organizationId: input.organizationId },
      });
      if (!lease) throw new BadRequestException('Lease not found');
    }
    let share: string | undefined;
    if (input.tenantSharePercent != null) {
      const s = new Decimal(input.tenantSharePercent);
      if (s.lt(0) || s.gt(100)) throw new BadRequestException('Tenant share must be 0–100');
      share = s.toFixed(3);
    }
    return this.prisma.maintenanceRequest.update({
      where: { id: existing.id },
      data: {
        categoryId: input.categoryId === undefined ? undefined : input.categoryId,
        priorityId: input.priorityId === undefined ? undefined : input.priorityId,
        title: input.title ?? undefined,
        description: input.description === undefined ? undefined : input.description,
        leaseId: input.leaseId === undefined ? undefined : input.leaseId,
        costResponsibility: input.costResponsibility ?? undefined,
        tenantSharePercent: share,
        estimatedCost: input.estimatedCost === undefined ? undefined : this.cost(input.estimatedCost)?.toFixed(2) ?? null,
        actualCost: input.actualCost === undefined ? undefined : this.cost(input.actualCost)?.toFixed(2) ?? null,
      },
    });
  }

  /** Guarded lifecycle move — refuses illegal transitions. */
  async transition(input: { organizationId: string; id: string; toStatus: string }): Promise<MaintenanceRequest> {
    const existing = await this.prisma.maintenanceRequest.findFirst({
      where: { id: input.id, organizationId: input.organizationId },
    });
    if (!existing) throw new NotFoundException('Maintenance request not found');
    const allowed = REQUEST_TRANSITIONS[existing.status] ?? [];
    if (!allowed.includes(input.toStatus)) {
      throw new BadRequestException(`Cannot move a ${existing.status} request to ${input.toStatus}`);
    }
    const updated = await this.prisma.maintenanceRequest.update({ where: { id: existing.id }, data: { status: input.toStatus } });
    try {
      await this.events.emitAsync('notify', {
        event: 'MAINTENANCE_STATUS_CHANGED',
        organizationId: input.organizationId,
        relatedType: 'MAINTENANCE_REQUEST',
        relatedId: updated.id,
      });
    } catch {
      // notifications are best-effort
    }
    return updated;
  }

  /** Dispatch a work order (to internal staff or a named external contractor). */
  async addTask(input: {
    organizationId: string;
    requestId: string;
    title: string;
    assignedToId?: string | null;
    assignedVendor?: string | null;
    scheduledDate?: string | null;
    note?: string | null;
  }): Promise<MaintenanceTask> {
    const request = await this.prisma.maintenanceRequest.findFirst({
      where: { id: input.requestId, organizationId: input.organizationId },
    });
    if (!request) throw new NotFoundException('Maintenance request not found');
    return this.prisma.maintenanceTask.create({
      data: {
        requestId: input.requestId,
        title: input.title,
        assignedToId: input.assignedToId ?? null,
        assignedVendor: input.assignedVendor ?? null,
        scheduledDate: input.scheduledDate ? new Date(input.scheduledDate) : null,
        note: input.note ?? null,
      },
    });
  }

  async updateTask(input: {
    organizationId: string;
    taskId: string;
    title?: string;
    status?: string;
    assignedToId?: string | null;
    assignedVendor?: string | null;
    scheduledDate?: string | null;
    note?: string | null;
  }): Promise<MaintenanceTask> {
    const task = await this.prisma.maintenanceTask.findFirst({
      where: { id: input.taskId, request: { organizationId: input.organizationId } },
    });
    if (!task) throw new NotFoundException('Task not found');
    if (input.status != null && !TASK_STATUSES.includes(input.status)) {
      throw new BadRequestException('Invalid task status');
    }
    return this.prisma.maintenanceTask.update({
      where: { id: task.id },
      data: {
        title: input.title ?? undefined,
        status: input.status ?? undefined,
        assignedToId: input.assignedToId === undefined ? undefined : input.assignedToId,
        assignedVendor: input.assignedVendor === undefined ? undefined : input.assignedVendor,
        scheduledDate: input.scheduledDate === undefined ? undefined : input.scheduledDate ? new Date(input.scheduledDate) : null,
        note: input.note === undefined ? undefined : input.note,
      },
    });
  }

  /** Cost-recovery bridge: turns a tenant-borne actual cost into a reviewable
   * R&M draft invoice on the tenant's lease. It does NOT post to the ledger —
   * the admin issues the draft, going through the same balanced-entry path as
   * every other charge, so the recovery is fully traceable and never doubled.
   *
   * The repair slips and receipts filed on the request go onto the line that
   * charges it, so they print with the note as its supporting documents and the
   * tenant sees what they are paying for. Each file is copied, not shared — a
   * stored file belongs to one row — and copied before the transaction, which
   * file writes cannot join: if the charge then fails, the copies are removed. */
  async chargeToTenant(input: { organizationId: string; id: string }): Promise<{ invoiceId: string }> {
    const evidence = await this.prisma.attachment.findMany({
      where: { organizationId: input.organizationId, ownerType: 'MAINTENANCE_REQUEST', ownerId: input.id },
      orderBy: { createdAt: 'asc' },
    });
    const typeName = new Map(
      (
        await this.prisma.referenceValue.findMany({
          where: { id: { in: evidence.map((f) => f.documentTypeId).filter((v): v is string => !!v) } },
          select: { id: true, nameEn: true },
        })
      ).map((v) => [v.id, v.nameEn]),
    );
    const copies: { from: (typeof evidence)[number]; storageKey: string }[] = [];
    try {
      for (const from of evidence) {
        copies.push({ from, storageKey: await this.storage.save(await this.storage.read(from.storageKey), this.storage.extForMime(from.mimeType) ?? 'bin') });
      }
      return await this.charge(input, copies, typeName);
    } catch (err) {
      await Promise.all(copies.map((c) => this.storage.remove(c.storageKey).catch(() => undefined)));
      throw err;
    }
  }

  private charge(
    input: { organizationId: string; id: string },
    copies: { from: { filename: string; mimeType: string; sizeBytes: number; caption: string | null; documentTypeId: string | null; uploadedByUserId: string | null }; storageKey: string }[],
    typeName: Map<string, string>,
  ): Promise<{ invoiceId: string }> {
    return this.prisma.$transaction(async (tx) => {
      const req = await tx.maintenanceRequest.findFirst({
        where: { id: input.id, organizationId: input.organizationId },
      });
      if (!req) throw new NotFoundException('Maintenance request not found');
      if (req.chargedInvoiceId) throw new BadRequestException('This request has already been charged');
      if (req.costResponsibility === 'LANDLORD') throw new BadRequestException('A landlord-borne cost is not billable to the tenant');
      if (!req.actualCost) throw new BadRequestException('Record the actual cost before charging');
      if (!req.leaseId) throw new BadRequestException('Link this request to a lease/tenancy before charging');
      if (req.status !== 'COMPLETED' && req.status !== 'CLOSED') {
        throw new BadRequestException('Complete the work before charging the tenant');
      }

      const sharePct = req.costResponsibility === 'TENANT' ? new Decimal(100) : new Decimal(req.tenantSharePercent.toString());
      const chargeable = toCents(new Decimal(req.actualCost.toString()).times(sharePct).dividedBy(100));
      if (chargeable.lte(0)) throw new BadRequestException('Nothing to charge (share resolves to 0)');

      const lease = await tx.lease.findFirst({ where: { id: req.leaseId, organizationId: input.organizationId } });
      if (!lease) throw new BadRequestException('Lease not found');

      const rm = await tx.chargeType.findFirst({
        where: { organizationId: input.organizationId, code: RM_CODE, isActive: true },
      });
      if (!rm) throw new BadRequestException('Repairs & Maintenance (RM) charge type is not configured');

      const now = new Date();
      // Hong Kong's month, not UTC's. Between midnight and 08:00 on the 1st the
      // two disagree, and stamping the previous month lands the recovery in a
      // period that has usually been billed already — where the monthly run
      // skips the lease entirely because a note exists for it.
      const hk = hkToday();
      const billingPeriod = `${hk.getUTCFullYear()}-${String(hk.getUTCMonth() + 1).padStart(2, '0')}`;
      const dueDate = new Date(now.getTime() + 14 * 24 * 3600 * 1000);

      const invoice = await tx.invoice.create({
        data: {
          organizationId: input.organizationId,
          leaseId: lease.id,
          bankAccountId: lease.bankAccountId,
          status: 'DRAFT',
          currency: lease.currency,
          billingPeriod,
          unitScope: req.unitId ? [req.unitId] : Prisma.DbNull,
          dueDate,
          note: `Maintenance recovery: ${req.title}`,
          lines: {
            create: {
              kind: 'CHARGE',
              chargeTypeId: rm.id,
              description: `Maintenance: ${req.title}`,
              amount: chargeable.toFixed(2),
              sortOrder: 0,
              // Marked as human intent, which is what it is — somebody decided
              // this repair is the tenant's. Rebuilding a note replaces every
              // CHARGE that is NOT so marked, so without this the recovery line
              // is deleted and cannot be raised again: chargedInvoiceId below is
              // stamped once and never cleared, so chargeToTenant refuses forever.
              meta: { adjustment: true },
            },
          },
        },
        include: { lines: { select: { id: true } } },
      });
      if (copies.length) {
        await tx.attachment.createMany({
          data: copies.map(({ from, storageKey }) => ({
            organizationId: input.organizationId,
            ownerType: 'INVOICE_LINE' as const,
            ownerId: invoice.lines[0].id,
            filename: from.filename,
            mimeType: from.mimeType,
            sizeBytes: from.sizeBytes,
            storageKey,
            // What it is, as the note's English evidence page names it.
            caption: [from.documentTypeId ? typeName.get(from.documentTypeId) : null, from.caption].filter(Boolean).join(' — ') || null,
            uploadedByUserId: from.uploadedByUserId,
          })),
        });
      }

      // Compare-and-swap: only the first concurrent charge wins. If another
      // transaction already claimed it, count is 0 → throw → this whole
      // transaction (including the invoice just created above) rolls back, so no
      // duplicate R&M draft survives.
      const claim = await tx.maintenanceRequest.updateMany({
        where: { id: req.id, chargedInvoiceId: null },
        data: { chargedInvoiceId: invoice.id },
      });
      if (claim.count !== 1) throw new BadRequestException('This request has already been charged');
      return { invoiceId: invoice.id };
    });
  }
}
