import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ClsService } from 'nestjs-cls';
import { BookingEntity } from '../../../entities/booking.entity';
import { MailerService } from '../../mailer/mailer.service';
import { MovementChartExportService } from './movement-chart-export.service';
import { DriverAssignmentService } from './driver-assignment.service';
import {
  CLS_TENANT_ID,
  CLS_USER_ID,
  CLS_USER_ROLE_ID,
  CLS_USER_ROLE_NAME,
  CLS_USER_PERMISSIONS,
  CLS_ROLE_VIEW_ALL_BOOKINGS_QUERIES,
} from '../../../common/cls/cls.constants';

/** Days covered by the nightly mail: tomorrow + the 2 days after. */
export const MD_DIGEST_DAYS = 3;
/** The nightly run is anchored to the client's local day. */
export const MD_DIGEST_TIMEZONE = 'Asia/Dubai';

interface AdminRecipient {
  id: string;
  name: string | null;
  email: string;
  role_id: string;
  role_name: string;
  view_all: boolean;
}

function esc(v: unknown): string {
  return String(v ?? '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

/** `YYYY-MM-DD` of `base` in `timeZone`, shifted by `addDays`. */
export function localDay(base: Date, timeZone: string, addDays = 0): string {
  const parts = new Intl.DateTimeFormat('en-CA', {
    timeZone,
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  }).format(base);
  const d = new Date(`${parts}T00:00:00Z`);
  d.setUTCDate(d.getUTCDate() + addDays);
  return d.toISOString().slice(0, 10);
}

const fmt = (iso: string) => iso.split('-').reverse().join('/');

/**
 * Nightly Movement Dashboard mail (client 2026-10-17): every Admin of a
 * tenant gets the Excel export for the next 3 days as an attachment,
 * with a per-day summary in the body.
 *
 * Runs outside a request, so it opens its own CLS context per tenant
 * (tenancy.md cron caution) and acts as one of that tenant's Admins —
 * the export then applies the same permissions and visibility an Admin
 * sees on screen (costs included).
 */
@Injectable()
export class MovementChartDigestService {
  private readonly logger = new Logger(MovementChartDigestService.name);

  constructor(
    @InjectRepository(BookingEntity)
    private readonly bookingRepo: Repository<BookingEntity>,
    private readonly cls: ClsService,
    private readonly mailer: MailerService,
    private readonly mdExport: MovementChartExportService,
    private readonly driverAssignment: DriverAssignmentService,
  ) {}

  /** Every active tenant; one tenant's failure does not stop the rest. */
  async sendAllTenants(
    now = new Date(),
  ): Promise<{ sent: number; skipped: number; failed: number }> {
    const tenants = (await this.bookingRepo.manager.query(
      `SELECT id FROM tenants WHERE is_active = true ORDER BY id`,
    )) as Array<{ id: string }>;
    const result = { sent: 0, skipped: 0, failed: 0 };
    for (const t of tenants) {
      try {
        const r = await this.sendForTenant(t.id, now);
        if (r.recipients > 0) result.sent += 1;
        else result.skipped += 1;
      } catch (err) {
        result.failed += 1;
        this.logger.error(
          `Movement Dashboard mail failed for tenant ${t.id}`,
          err instanceof Error ? err.stack : String(err),
        );
      }
    }
    return result;
  }

  /** Build + mail the next-3-days export for one tenant. */
  async sendForTenant(
    tenantId: string,
    now = new Date(),
  ): Promise<{ recipients: number; from: string; to: string }> {
    const from = localDay(now, MD_DIGEST_TIMEZONE, 1);
    const to = localDay(now, MD_DIGEST_TIMEZONE, MD_DIGEST_DAYS);
    const admins = await this.adminRecipients(tenantId);
    if (admins.length === 0) return { recipients: 0, from, to };

    const actingAs = admins[0];
    await this.cls.run({ ifNested: 'override' }, async () => {
      this.cls.set(CLS_TENANT_ID, tenantId);
      this.cls.set(CLS_USER_ID, actingAs.id);
      this.cls.set(CLS_USER_ROLE_ID, actingAs.role_id);
      this.cls.set(CLS_USER_ROLE_NAME, actingAs.role_name);
      this.cls.set(CLS_ROLE_VIEW_ALL_BOOKINGS_QUERIES, actingAs.view_all);
      this.cls.set(CLS_USER_PERMISSIONS, await this.rolePermissions(tenantId, actingAs.role_id));

      const chart = await this.driverAssignment.getMovementChart(undefined, from, { date_to: to });
      const { buffer, filename } = await this.mdExport.buildWorkbook(undefined, from, to);
      const company = (await this.bookingRepo.manager.query(
        `SELECT company_name FROM tenant_settings WHERE tenant_id = $1 LIMIT 1`,
        [tenantId],
      )) as Array<{ company_name: string | null }>;

      await this.mailer.send({
        to: admins.map((a) => ({ email: a.email, ...(a.name ? { name: a.name } : {}) })),
        subject: `Movement Dashboard ${fmt(from)} – ${fmt(to)}`,
        html: this.buildHtml(chart, from, to),
        fromName: company[0]?.company_name || undefined,
        attachments: [{ name: filename, content: buffer }],
      });
    });
    this.logger.log(
      `Movement Dashboard mail ${from}..${to} sent to ${admins.length} admin(s) of ${tenantId}`,
    );
    return { recipients: admins.length, from, to };
  }

  /** Active users on the tenant's system Admin role. */
  private async adminRecipients(tenantId: string): Promise<AdminRecipient[]> {
    return (await this.bookingRepo.manager.query(
      `SELECT u.id, u.name, u.email, r.id AS role_id, r.name AS role_name,
              COALESCE(r.view_all_bookings_queries, false) AS view_all
         FROM users u
         JOIN roles r ON r.id = u.role_id AND r.tenant_id = u.tenant_id
        WHERE u.tenant_id = $1
          AND u.is_deleted = false AND u.is_active = true
          AND COALESCE(u.email, '') <> ''
          AND r.is_deleted = false AND r.is_system = true AND r.name = 'Admin'
        ORDER BY u.created_at`,
      [tenantId],
    )) as AdminRecipient[];
  }

  private async rolePermissions(tenantId: string, roleId: string): Promise<Record<string, string>> {
    const rows = (await this.bookingRepo.manager.query(
      `SELECT module, access_level FROM role_permissions
        WHERE role_id = $1 AND tenant_id = $2 AND is_deleted = false`,
      [roleId, tenantId],
    )) as Array<{ module: string; access_level: string }>;
    return Object.fromEntries(rows.map((r) => [r.module, r.access_level]));
  }

  /** Per-day counts so the mail is useful without opening the file. */
  private buildHtml(
    chart: Awaited<ReturnType<DriverAssignmentService['getMovementChart']>>,
    from: string,
    to: string,
  ): string {
    type Op = {
      type?: string;
      date?: unknown;
      supplier_id?: string | null;
      supplier_name?: string | null;
    };
    const days: string[] = [];
    for (let d = from; d <= to; d = localDay(new Date(`${d}T12:00:00Z`), 'UTC', 1)) days.push(d);
    const dayOf = (v: unknown) => String(v ?? '').slice(0, 10);
    const transports = (chart.by_booking || []).flatMap((b: { ops: Op[] }) =>
      b.ops.filter((o) => o.type === 'transport'),
    );
    const activities = (chart.by_activity || []).flatMap((g: { items: Op[] }) => g.items);
    const rows = days
      .map((d) => {
        const t = transports.filter((o: Op) => dayOf(o.date) === d);
        const a = activities.filter((o: Op) => dayOf(o.date) === d);
        const open = [...t, ...a].filter((o: Op) => !o.supplier_id && !o.supplier_name).length;
        return `<tr><td>${esc(fmt(d))}</td><td align="right">${t.length}</td><td align="right">${a.length}</td><td align="right">${open}</td></tr>`;
      })
      .join('');
    return `
      <p>Movement Dashboard for <b>${esc(fmt(from))}</b> to <b>${esc(fmt(to))}</b> — the Excel export is attached.</p>
      <table cellpadding="6" style="border-collapse:collapse;font-family:Arial,sans-serif;font-size:14px" border="1">
        <tr style="background:#f1f5f9"><th align="left">Date</th><th>Transfers</th><th>Activities</th><th>No supplier yet</th></tr>
        ${rows}
      </table>
      <p style="color:#6b7280;font-size:12px">Sent automatically every night to Admins.</p>`;
  }
}
