import { Injectable, NotFoundException } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { StorageService } from '../attachments/storage.service';
import { hkIsoDay, parseDay } from '../common/hk-date';
import { DocumentService } from '../documents/document.service';
import { PrismaService } from '../prisma/prisma.service';
import { ReportsService } from '../reports/reports.service';
import type { StatementQuery } from '../reports/reports.types';

/** One sent statement as the lists show it. */
export interface SentStatementRow {
  id: string;
  leaseId: string;
  leaseReference: string;
  from: string;
  to: string;
  currency: string;
  closing: string;
  sentAt: Date;
}

/**
 * Monthly statements sent to tenants. Sending renders each lease's statement
 * to PDF and keeps the file, so the portal shows the tenant exactly what the
 * office sent — the ledger and the template can change afterwards without
 * changing what the tenant was given. The same lease and period sent again
 * replaces it. The figures come from the reports service and the layout from
 * the document service; this only keeps and hands out the result.
 */
@Injectable()
export class StatementsService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly reports: ReportsService,
    private readonly documents: DocumentService,
    private readonly storage: StorageService,
    private readonly events: EventEmitter2,
  ) {}

  /** Sends each lease's statement for the period, one lease at a time: a
   *  failure part way leaves the ones before it sent. Each tenant is notified
   *  as theirs is sent. */
  async send(input: { organizationId: string; query: StatementQuery & { leaseIds: string[] }; sentById?: string | null }): Promise<{ sent: number }> {
    const { organizationId, query } = input;
    const { statements } = await this.reports.statements(organizationId, query);
    const order = new Map(query.leaseIds.map((id, i) => [id, i]));
    statements.sort((a, b) => order.get(a.leaseId)! - order.get(b.leaseId)!);
    const periodFrom = parseDay(query.from);
    const periodTo = parseDay(query.to);

    let sent = 0;
    for (const s of statements) {
      const pdf = await this.documents.statementsPdf(organizationId, [s], query);
      const storageKey = await this.storage.save(pdf, 'pdf');
      let replaced: string | null = null;
      let id: string;
      try {
        const data = { currency: s.currency, closing: s.closing, storageKey, sizeBytes: pdf.length, sentById: input.sentById ?? null, sentAt: new Date() };
        const row = await this.prisma.$transaction(async (tx) => {
          const old = await tx.sentStatement.findUnique({ where: { leaseId_periodFrom_periodTo: { leaseId: s.leaseId, periodFrom, periodTo } } });
          replaced = old?.storageKey ?? null;
          return old
            ? tx.sentStatement.update({ where: { id: old.id }, data })
            : tx.sentStatement.create({ data: { organizationId, leaseId: s.leaseId, periodFrom, periodTo, ...data } });
        });
        id = row.id;
      } catch (err) {
        await this.storage.remove(storageKey);
        throw err;
      }
      if (replaced) await this.storage.remove(replaced);
      await this.events.emitAsync('notify', { event: 'STATEMENT_SENT', organizationId, relatedType: 'STATEMENT', relatedId: id });
      sent++;
    }
    return { sent };
  }

  /** Takes a sent statement back out of the tenant's portal. */
  async withdraw(organizationId: string, id: string): Promise<void> {
    const row = await this.prisma.sentStatement.findFirst({ where: { id, organizationId } });
    if (!row) throw new NotFoundException('Statement not found');
    await this.prisma.sentStatement.delete({ where: { id: row.id } });
    await this.storage.remove(row.storageKey);
  }

  /** The statements sent for exactly this period — what the office's list marks as sent. */
  forPeriod(organizationId: string, from: string, to: string): Promise<SentStatementRow[]> {
    return this.list({ organizationId, periodFrom: parseDay(from), periodTo: parseDay(to) });
  }

  /** Everything sent to a tenant, newest period first. */
  forTenant(tenantId: string): Promise<SentStatementRow[]> {
    return this.list({ lease: { tenantId } });
  }

  /** The PDF as it was sent, and whose it is. */
  async file(organizationId: string, id: string): Promise<{ pdf: Buffer; filename: string; tenantId: string }> {
    const row = await this.prisma.sentStatement.findFirst({
      where: { id, organizationId },
      select: { storageKey: true, periodTo: true, lease: { select: { reference: true, tenantId: true } } },
    });
    if (!row) throw new NotFoundException('Statement not found');
    return {
      pdf: await this.storage.read(row.storageKey),
      filename: `statement-${row.lease.reference}-${hkIsoDay(row.periodTo)}.pdf`,
      tenantId: row.lease.tenantId,
    };
  }

  private async list(where: NonNullable<Parameters<PrismaService['sentStatement']['findMany']>[0]>['where']): Promise<SentStatementRow[]> {
    const rows = await this.prisma.sentStatement.findMany({
      where,
      orderBy: [{ periodTo: 'desc' }, { sentAt: 'desc' }],
      select: { id: true, leaseId: true, periodFrom: true, periodTo: true, currency: true, closing: true, sentAt: true, lease: { select: { reference: true } } },
    });
    return rows.map((r) => ({
      id: r.id,
      leaseId: r.leaseId,
      leaseReference: r.lease.reference,
      from: hkIsoDay(r.periodFrom),
      to: hkIsoDay(r.periodTo),
      currency: r.currency,
      closing: r.closing.toFixed(2),
      sentAt: r.sentAt,
    }));
  }
}
