import { Inject, Injectable, Logger } from '@nestjs/common';
import {
  SAR_REPORT_REPOSITORY,
  ISarReportRepository,
} from '../../domain/repositories/sar-report.repository.interface';
import {
  AUDIT_LOG_REPOSITORY,
  IAuditLogRepository,
} from '../../domain/repositories/audit-log.repository.interface';
import {
  AML_ALERT_REPOSITORY,
  IAmlAlertRepository,
} from '../../domain/repositories/aml-alert.repository.interface';
import {
  TRAVEL_RULE_REPOSITORY,
  ITravelRuleRepository,
} from '../../domain/repositories/travel-rule.repository.interface';
import {
  AUDIT_LOGGER_SERVICE,
  IAuditLoggerService,
} from '../../domain/ports/audit-logger.interface';

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

  constructor(
    @Inject(SAR_REPORT_REPOSITORY)
    private readonly sarRepo: ISarReportRepository,
    @Inject(AUDIT_LOG_REPOSITORY)
    private readonly auditRepo: IAuditLogRepository,
    @Inject(AML_ALERT_REPOSITORY)
    private readonly alertRepo: IAmlAlertRepository,
    @Inject(TRAVEL_RULE_REPOSITORY)
    private readonly travelRepo: ITravelRuleRepository,
    @Inject(AUDIT_LOGGER_SERVICE)
    private readonly auditLogger: IAuditLoggerService,
  ) {}

  // ───────────── SAR Management ─────────────

  /** List SAR reports (paginated, with optional status filter) */
  async listSarReports(page: number, limit: number, status?: string) {
    const [items, total] = await this.sarRepo.findPaginated(page, limit, { status });
    return { items, total, page, limit, totalPages: Math.ceil(total / limit) };
  }

  /** Create a new SAR report */
  async createSarReport(data: {
    alertId: string;
    userId: string;
    reportType: string;
    narrative: string;
  }) {
    const sar = this.sarRepo.create({
      ...data,
      filingStatus: 'draft',
    });
    const saved = await this.sarRepo.save(sar);
    this.logger.log(`SAR created: ${saved.id} for alert ${data.alertId}`);
    return saved;
  }

  // ───────────── Audit Logs ─────────────

  /** List admin action audit logs (paginated, with optional filters) */
  async listAuditLogs(
    page: number,
    limit: number,
    action?: string,
    adminId?: string,
    resource?: string,
    startDate?: string,
    endDate?: string,
  ) {
    const [items, total] = await this.auditRepo.findPaginated(page, limit, {
      action,
      adminId,
      resource,
      startDate,
      endDate,
    });
    return { items, total, page, limit, totalPages: Math.ceil(total / limit) };
  }

  // ───────────── Compliance Reports ─────────────

  /** List compliance reports (summary overview) */
  async listReports() {
    const [totalAlerts, openAlerts, totalSars, filedSars, travelRuleRecords] = await Promise.all([
      this.alertRepo.count(),
      this.alertRepo.count({ where: [{ status: 'open' as any }] }),
      this.sarRepo.count(),
      this.sarRepo.count({ where: { filingStatus: 'filed' } }),
      this.travelRepo.count(),
    ]);

    return {
      reports: [
        {
          type: 'aml_summary',
          title: 'AML Alert Summary',
          totalAlerts,
          openAlerts,
          resolvedAlerts: totalAlerts - openAlerts,
        },
        {
          type: 'sar_summary',
          title: 'SAR Filing Summary',
          totalSars,
          filedSars,
          draftSars: totalSars - filedSars,
        },
        {
          type: 'travel_rule_summary',
          title: 'Travel Rule Compliance',
          totalRecords: travelRuleRecords,
        },
      ],
    };
  }

  /** Generate a new compliance report (snapshot in time) */
  async generateReport(
    reportType: string,
    adminId: string,
    adminName: string,
    ipAddress?: string,
  ) {
    const timestamp = new Date().toISOString();

    let reportData: any;
    switch (reportType) {
      case 'aml':
        const [alertCount, highRisk] = await Promise.all([
          this.alertRepo.count(),
          this.alertRepo.countHighRisk(70),
        ]);
        reportData = { alertCount, highRiskCount: highRisk, generatedAt: timestamp };
        break;
      case 'sar':
        const sarCount = await this.sarRepo.count();
        const filedCount = await this.sarRepo.count({ where: { filingStatus: 'filed' } });
        reportData = { totalSars: sarCount, filedSars: filedCount, generatedAt: timestamp };
        break;
      case 'travel_rule':
        const trCount = await this.travelRepo.count();
        reportData = { totalRecords: trCount, generatedAt: timestamp };
        break;
      default:
        reportData = { type: reportType, status: 'unsupported', generatedAt: timestamp };
    }

    // Audit log the report generation via shared service
    await this.auditLogger.log({
      adminId,
      adminName,
      action: 'generate_report',
      resource: 'compliance_report',
      resourceId: null,
      ipAddress,
      details: { reportType, ...reportData },
    });

    this.logger.log(`Report generated: type=${reportType} by admin=${adminId}`);
    return { reportType, ...reportData };
  }

  // ───────────── SEC Filing ─────────────

  /** Get SEC filing status */
  async getSecFilingStatus() {
    return {
      registrationStatus: 'active',
      lastFiling: '2024-Q4',
      nextDeadline: '2025-03-31',
      filings: [
        { type: 'Form ATS-N', status: 'filed', date: '2024-12-15' },
        { type: 'Reg D Exemption', status: 'active', date: '2024-06-01' },
        { type: 'Annual Report', status: 'pending', dueDate: '2025-03-31' },
      ],
    };
  }

  // ───────────── License Management ─────────────

  /** Get license management info */
  async getLicenses() {
    return {
      licenses: [
        {
          name: 'Money Transmitter License',
          jurisdiction: 'Federal',
          status: 'active',
          issuedAt: '2023-01-15',
          expiresAt: '2026-01-15',
        },
        {
          name: 'ATS License',
          jurisdiction: 'SEC',
          status: 'active',
          issuedAt: '2023-06-01',
          expiresAt: '2025-06-01',
        },
        {
          name: 'State MSB License',
          jurisdiction: 'New York',
          status: 'pending_renewal',
          issuedAt: '2022-11-01',
          expiresAt: '2025-11-01',
        },
      ],
    };
  }

  // ───────────── Tax Compliance ─────────────

  /** Get tax compliance overview */
  async getTaxCompliance() {
    return {
      taxYear: 2024,
      form1099Filed: 0,
      form1099Required: 0,
      costBasisReportsGenerated: 0,
      withholdingRate: 0.24,
      notes: 'Tax reporting infrastructure ready. No live transactions yet.',
    };
  }
}
