import { NextRequest, NextResponse } from 'next/server';
import { auditAction } from '@/features/foundation/audit-log/service';
import { getCrmDashboardData } from '@/features/crm/dashboard/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

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

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

function buildExcelTable(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 GET(request: NextRequest) {
  try {
    const { session, membership, organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDashboardExport
    });
    const searchParams = request.nextUrl.searchParams;
    const section = searchParams.get('section') ?? 'sales-ranking';
    const format = searchParams.get('format') ?? 'csv';
    const data = await getCrmDashboardData(
      {
        organizationId: organization.id,
        userId: session.user.id,
        membershipRole: membership.role,
        businessRole: membership.businessRole,
        permissions: membership.permissions
      },
      {
        dateFrom: searchParams.get('dateFrom'),
        dateTo: searchParams.get('dateTo'),
        branch: searchParams.get('branch'),
        salesman: searchParams.get('salesman'),
        projectPartyRole: searchParams.get('projectPartyRole'),
        productType: searchParams.get('productType')
      }
    );

    let rows: string[][] = [];

    if (section === 'revenue-analytics') {
      rows = [
        ['มิติรายงาน', 'รหัสลูกค้า', 'ชื่อลูกค้า', 'มูลค่าใบเสนอราคา', 'จำนวนใบเสนอราคา', 'มูลค่างานที่ชนะ'],
        ...[
          ['เจ้าของโครงการ', ...data.revenueAnalytics.topEndCustomers],
          ['ลูกค้าผู้รับใบเสนอราคา', ...data.revenueAnalytics.topBillingCustomers],
          ['ผู้รับเหมา', ...data.revenueAnalytics.topContractors],
          ['ที่ปรึกษา', ...data.revenueAnalytics.topConsultants]
        ].flatMap(([dimension, ...entries]) =>
          (entries as typeof data.revenueAnalytics.topEndCustomers).map((row) => [
            String(dimension),
            row.customerCode,
            row.customerName,
            String(row.revenue),
            String(row.quotationCount),
            String(row.wonRevenue)
          ])
        )
      ];
    } else if (section === 'pipeline-funnel') {
      rows = [
        ['ขั้นตอน', 'จำนวน', 'มูลค่า', 'อัตราการเปลี่ยนสถานะ'],
        ...data.funnel.map((row) => [
          row.label,
          String(row.count),
          String(row.value),
          row.conversionRate === null ? '' : String(row.conversionRate)
        ])
      ];
    } else {
      rows = [
        ['ฝ่ายขาย', 'จำนวนลีด', 'จำนวนโอกาสขาย', 'จำนวนใบเสนอราคา', 'จำนวนใบเสนอราคาที่อนุมัติแล้ว', 'มูลค่างานที่ชนะ', 'อัตราการเปลี่ยนสถานะ'],
        ...data.salesRanking.map((row) => [
          row.salesPersonName,
          String(row.leadCount),
          String(row.enquiryCount),
          String(row.quotationCount),
          String(row.approvedQuotations),
          String(row.wonRevenue),
          String(row.conversionRate)
        ])
      ];
    }

    await auditAction({
      organizationId: organization.id,
      userId: session.user.id,
      entityType: 'crm_dashboard_export',
      entityId: section,
      action: format === 'xls' ? 'export_excel' : 'export_csv',
      afterData: {
        section,
        format,
        filters: data.filters
      }
    });

    const body = format === 'xls' ? buildExcelTable(rows) : buildCsv(rows);
    const contentType =
      format === 'xls' ? 'application/vnd.ms-excel; charset=utf-8' : 'text/csv; charset=utf-8';
    const extension = format === 'xls' ? 'xls' : 'csv';

    return new NextResponse(body, {
      headers: {
        'Content-Type': contentType,
        'Content-Disposition': `attachment; filename="crm-dashboard-${section}.${extension}"`
      }
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: 'Unable to export CRM dashboard data' }, { status: 500 });
  }
}
