import { Injectable, Logger } from '@nestjs/common';
import type { NotificationChannel, NotificationEvent, NotificationStatus } from '@prisma/client';
import { formatCurrency } from '@rms/domain';
import { PrismaService } from '../prisma/prisma.service';
import { ChannelDispatcher } from './channel.dispatcher';
import { type NotifyPayload, renderTemplate } from './notification.constants';

interface Contact {
  name: string;
  email: string | null;
  phone: string | null;
}
interface BuiltContext {
  context: Record<string, string>;
  tenant: Contact | null;
}

@Injectable()
export class NotificationService {
  private readonly logger = new Logger('NotificationService');

  constructor(
    private readonly prisma: PrismaService,
    private readonly dispatcher: ChannelDispatcher,
  ) {}

  /** Fan an event out to its active templates, render, deliver, and record every
   * attempt in the outbox. Never throws — a notification failure must not affect
   * the money/business operation that triggered it. */
  async dispatch(payload: NotifyPayload): Promise<void> {
    try {
      const enabled = await this.getSetting(payload.organizationId, 'notification.enabled', true);
      if (enabled === false) return;

      const templates = await this.prisma.notificationTemplate.findMany({
        where: { organizationId: payload.organizationId, event: payload.event as NotificationEvent, isActive: true },
      });
      if (templates.length === 0) return;

      const built = await this.buildContext(payload.event, payload.relatedId);
      if (!built) return;

      const staff = await this.staffContact(payload.organizationId);

      for (const tpl of templates) {
        const contact = tpl.recipient === 'STAFF' ? staff : built.tenant;
        const address = tpl.channel === 'EMAIL' ? contact?.email ?? null : contact?.phone ?? null;
        const subject = tpl.subject ? renderTemplate(tpl.subject, built.context) : null;
        const body = renderTemplate(tpl.body, built.context);

        if (!address) {
          await this.record(payload, tpl.channel, `${tpl.recipient} (no ${tpl.channel === 'EMAIL' ? 'email' : 'phone'})`, subject, body, 'SKIPPED');
          continue;
        }
        const res = await this.dispatcher
          .send(tpl.channel, address, subject, body)
          .catch((e) => ({ ok: false, delivered: false, error: String(e) }));
        // SENT means a provider took it. With no provider wired up the message
        // was only logged, and recording that as SENT would put a timestamped
        // claim in the outbox that the tenant was told something they were not.
        const status = !res.ok ? 'FAILED' : res.delivered ? 'SENT' : 'SKIPPED';
        await this.record(payload, tpl.channel, address, subject, body, status, res.delivered && res.ok ? undefined : res.error);
      }
    } catch (err) {
      this.logger.error(`dispatch failed for ${payload.event}: ${err instanceof Error ? err.message : err}`);
    }
  }

  private async record(
    p: NotifyPayload,
    channel: NotificationChannel,
    recipient: string,
    subject: string | null,
    body: string,
    status: NotificationStatus,
    error?: string,
  ): Promise<void> {
    await this.prisma.notificationOutbox.create({
      data: {
        organizationId: p.organizationId,
        event: p.event as NotificationEvent,
        channel,
        recipient,
        subject,
        body,
        status,
        error: error ?? null,
        relatedType: p.relatedType,
        relatedId: p.relatedId,
        sentAt: status === 'SENT' ? new Date() : null,
      },
    });
  }

  private async buildContext(event: string, relatedId: string): Promise<BuiltContext | null> {
    if (event === 'INVOICE_ISSUED') {
      const inv = await this.prisma.invoice.findUnique({
        where: { id: relatedId },
        include: { lines: { select: { amount: true } }, lease: { include: { tenant: true } } },
      });
      if (!inv) return null;
      const total = inv.lines.reduce((s, l) => s + Number(l.amount.toString()), 0);
      const t = inv.lease.tenant;
      return {
        tenant: contactOf(t),
        context: {
          tenantName: t.nameZh ?? t.name,
          invoiceNumber: inv.number ?? inv.billingPeriod,
          amount: money(total, inv.currency),
          dueDate: inv.dueDate.toISOString().slice(0, 10),
          period: inv.billingPeriod,
        },
      };
    }
    if (event === 'RECEIPT_APPROVED' || event === 'RECEIPT_REJECTED' || event === 'RECEIPT_BOUNCED') {
      const r = await this.prisma.receipt.findUnique({ where: { id: relatedId } });
      if (!r) return null;
      const t = await this.prisma.tenant.findUnique({ where: { id: r.tenantId } });
      return {
        tenant: t ? contactOf(t) : null,
        context: {
          tenantName: t ? t.nameZh ?? t.name : '',
          receiptNumber: r.number,
          amount: money(Number(r.amount.toString()), r.currency),
          date: r.receivedDate.toISOString().slice(0, 10),
          reason: r.rejectionReason ?? '',
        },
      };
    }
    if (event === 'MAINTENANCE_STATUS_CHANGED') {
      const m = await this.prisma.maintenanceRequest.findUnique({
        where: { id: relatedId },
        include: { tenant: true, property: { select: { name: true } }, unit: { select: { name: true } } },
      });
      if (!m) return null;
      return {
        tenant: m.tenant ? contactOf(m.tenant) : null,
        context: {
          tenantName: m.tenant ? m.tenant.nameZh ?? m.tenant.name : '',
          title: m.title,
          status: m.status,
          property: m.property.name,
          unit: m.unit?.name ?? '',
        },
      };
    }
    if (event === 'STATEMENT_SENT') {
      const s = await this.prisma.sentStatement.findUnique({ where: { id: relatedId }, include: { lease: { include: { tenant: true } } } });
      if (!s) return null;
      const t = s.lease.tenant;
      return {
        tenant: contactOf(t),
        context: {
          tenantName: t.nameZh ?? t.name,
          leaseReference: s.lease.reference,
          period: `${s.periodFrom.toISOString().slice(0, 10)} – ${s.periodTo.toISOString().slice(0, 10)}`,
          balance: money(Number(s.closing.toString()), s.currency),
        },
      };
    }
    return null;
  }

  private async staffContact(organizationId: string): Promise<Contact | null> {
    const email = (await this.getSetting(organizationId, 'notification.staff_email', null)) as string | null;
    const phone = (await this.getSetting(organizationId, 'notification.staff_phone', null)) as string | null;
    if (!email && !phone) return null;
    return { name: 'Staff', email, phone };
  }

  private async getSetting(organizationId: string, key: string, fallback: unknown): Promise<unknown> {
    const row = await this.prisma.setting.findFirst({ where: { organizationId, key } });
    return row ? row.value : fallback;
  }
}

function contactOf(t: { name: string; nameZh: string | null; email: string | null; phone: string | null }): Contact {
  return { name: t.nameZh ?? t.name, email: t.email, phone: t.phone };
}

/** The document's own currency, not an assumption. Telling an SGD tenant they
 *  owe "HK$" is wrong on the one line of the message that has to be right. */
function money(n: number, currency: string): string {
  return formatCurrency(n, currency);
}
