import { auditAction } from '@/features/foundation/audit-log/service';

function escapeCsv(value: string | number | null | undefined) {
  const text = value === null || value === undefined ? '' : String(value);
  return `"${text.replaceAll('"', '""')}"`;
}

export function buildReportCsv(rows: string[][]) {
  return rows.map((row) => row.map((cell) => escapeCsv(cell)).join(',')).join('\n');
}

export function buildReportExcel(rows: string[][]) {
  const body = rows
    .map(
      (row, rowIndex) =>
        `<tr>${row
          .map((cell) => (rowIndex === 0 ? `<th>${cell}</th>` : `<td>${cell}</td>`))
          .join('')}</tr>`
    )
    .join('');

  return `<!DOCTYPE html><html><head><meta charset="utf-8" /></head><body><table>${body}</table></body></html>`;
}

export async function auditReportExport(input: {
  organizationId: string;
  userId: string;
  reportCode: string;
  format: 'csv' | 'xls';
  filters?: Record<string, unknown>;
  recordCount?: number;
}) {
  await auditAction({
    organizationId: input.organizationId,
    userId: input.userId,
    entityType: 'crm_report',
    entityId: input.reportCode,
    action: input.format === 'xls' ? 'export_pipeline_report_excel' : 'export_pipeline_report_csv',
    afterData: {
      reportCode: input.reportCode,
      filters: input.filters ?? {},
      userId: input.userId,
      recordCount: input.recordCount ?? 0
    }
  });
}
