import { BadRequestException, Injectable } from '@nestjs/common';
import ExcelJS from 'exceljs';
import { DealStage, LeadStatus } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { RequestTenantContext, TenantQueryHelper } from '../../common/tenancy/tenant-query.helper';
import { NumberingService } from '../numbering/numbering.service';
import { SERVICE_INTERESTS, LEAD_SOURCES } from '../leads/lead.constants';
import { PHONE_PATTERN } from '../../common/dto/field-transforms';
import { ImportCommitDto, ImportPreviewDto } from './dto/import.dto';
import { escapeCsvCell, parseCsv } from './csv-helper';

@Injectable()
export class DataImportService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly tenant: TenantQueryHelper,
    private readonly numbering: NumberingService,
  ) {}

  // Previews and validates uploaded CSV records before database insertion.
  async previewImport(ctx: RequestTenantContext, dto: ImportPreviewDto) {
    const { headers, rows } = parseCsv(dto.csvContent);

    if (rows.length === 0) {
      throw new BadRequestException('CSV file is empty or missing headers');
    }

    const errors: Array<{ row: number; field: string; message: string }> = [];
    const rowErrorsMap = new Map<number, string[]>();

    if (dto.entity === 'leads') {
      const hasName = headers.includes('name');
      const hasService = headers.includes('serviceinterest') || headers.includes('service') || headers.includes('service_interest');
      const hasEmailOrPhone = headers.includes('email') || headers.includes('phone');

      if (!hasName) {
        errors.push({ row: 1, field: 'name', message: 'Header "name" is required for leads import' });
      }
      if (!hasService) {
        errors.push({ row: 1, field: 'serviceInterest', message: 'Header "serviceInterest" is required. Service interest is mandatory for all leads.' });
      }
      if (!hasEmailOrPhone) {
        errors.push({ row: 1, field: 'email', message: 'At least one header of "email" or "phone" is required for leads import' });
      }

      const tenantId = this.tenant.getRequiredTenantId(ctx);
      const [existingLeads, dbServices] = await Promise.all([
        this.prisma.lead.findMany({
          where: this.tenant.scopeWhere(ctx),
          select: { email: true, phone: true },
        }),
        this.prisma.service.findMany({
          where: { tenantId, isActive: true },
          select: { name: true },
        }),
      ]);

      const dbEmails = new Set(existingLeads.filter((l) => l.email).map((l) => l.email.toLowerCase().trim()));
      const dbPhones = new Set(existingLeads.filter((l) => l.phone).map((l) => l.phone!.trim().replace(/[\s\-()]/g, '')));

      // Prioritize organization's actual database services from Services catalog
      const activeServiceNames = dbServices.map((s) => s.name);
      const validServices = activeServiceNames.length > 0 ? activeServiceNames : Array.from(new Set(SERVICE_INTERESTS));
      const validServicesLower = new Map<string, string>();
      validServices.forEach((s) => validServicesLower.set(s.toLowerCase().trim(), s));

      const validSourcesLower = new Map<string, string>();
      LEAD_SOURCES.forEach((s) => validSourcesLower.set(s.toLowerCase().trim(), s));

      const statusMap: Record<string, LeadStatus> = {
        new: LeadStatus.NEW,
        'new enquiry': LeadStatus.NEW,
        contacted: LeadStatus.CONTACTED,
        'follow-up': LeadStatus.CONTACTED,
        'follow up': LeadStatus.CONTACTED,
        'follow-up in progress': LeadStatus.CONTACTED,
        qualified: LeadStatus.QUALIFIED,
        'requirement approved': LeadStatus.QUALIFIED,
        nurturing: LeadStatus.NURTURING,
        discussion: LeadStatus.NURTURING,
        'discussion / demo scheduled': LeadStatus.NURTURING,
        unqualified: LeadStatus.UNQUALIFIED,
        dropped: LeadStatus.UNQUALIFIED,
        'not interested / dropped': LeadStatus.UNQUALIFIED,
      };

      const seenEmails = new Set<string>();
      const seenPhones = new Set<string>();
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

      rows.forEach((r, idx) => {
        const tableRowNum = idx + 1;
        const excelLineNum = idx + 2;
        const rowMistakes: string[] = [];

        const addMistake = (field: string, msg: string) => {
          rowMistakes.push(msg);
          errors.push({
            row: tableRowNum,
            field,
            message: `Row ${tableRowNum} (Excel line ${excelLineNum}): ${msg}`,
          });
        };

        const name = (r.name || '').trim();
        const email = (r.email || '').trim().toLowerCase();
        const phone = (r.phone || '').trim();
        const rawService = (r.serviceinterest || r.service || r.service_interest || '').trim();
        const rawSource = (r.source || '').trim();
        const rawStatus = (r.status || '').trim().toLowerCase();
        const rawEstValue = (r.estimatedvalue || r.estimated_value || r.value || '').trim().replace(/,/g, '');
        const rawFollowUp = (r.nextfollowupat || r.next_follow_up || r.followup || '').trim();

        if (!name) {
          addMistake('name', 'Full name is required');
        } else if (name.length > 200) {
          addMistake('name', 'Name must be 200 characters or fewer');
        }

        if (!email && !phone) {
          addMistake('email', 'At least Email or Phone is required');
        }

        if (email) {
          if (!emailRegex.test(email)) {
            addMistake('email', `Invalid email format "${r.email}"`);
          } else if (dbEmails.has(email)) {
            addMistake('email', `Lead with email "${r.email}" already exists in CRM (Duplicate)`);
          } else if (seenEmails.has(email)) {
            addMistake('email', `Email "${r.email}" appears multiple times in file (Duplicate)`);
          }
          seenEmails.add(email);
        }

        if (phone) {
          if (!PHONE_PATTERN.test(phone)) {
            addMistake('phone', `Phone "${r.phone}" is not a valid phone number (digits, spaces, +, - or brackets only)`);
          }
          const normPhone = phone.replace(/[\s\-()]/g, '');
          if (normPhone) {
            if (dbPhones.has(normPhone)) {
              addMistake('phone', `Lead with phone "${r.phone}" already exists in CRM (Duplicate)`);
            } else if (seenPhones.has(normPhone)) {
              addMistake('phone', `Phone "${r.phone}" appears multiple times in file (Duplicate)`);
            }
            seenPhones.add(normPhone);
          }
        }

        // Service Interest is mandatory and matched against tenant database services
        if (!rawService) {
          const sampleList = validServices.join(', ');
          addMistake('serviceInterest', `Service is required. Active services: ${sampleList}`);
        } else if (!validServicesLower.has(rawService.toLowerCase())) {
          const sampleList = validServices.join(', ');
          addMistake('serviceInterest', `Service "${rawService}" is not recognized. Active services in catalog: ${sampleList}`);
        }

        // Source validation
        if (rawSource) {
          const isCustomOther = rawSource.toLowerCase().startsWith('other');
          const matchedSource = validSourcesLower.get(rawSource.toLowerCase());
          if (!matchedSource && !isCustomOther) {
            addMistake('source', `Source "${r.source}" is invalid. Allowed sources: ${LEAD_SOURCES.join(', ')}`);
          }
        }

        if (rawStatus && !statusMap[rawStatus]) {
          addMistake('status', `Status "${r.status}" is invalid. Allowed: New Enquiry, Follow-up, Qualified, Discussion, Dropped`);
        }

        if (rawEstValue) {
          const num = Number(rawEstValue);
          if (isNaN(num) || num < 0) {
            addMistake('estimatedValue', 'Estimated value must be a valid positive number');
          }
        }

        if (rawFollowUp) {
          const parsedDate = new Date(rawFollowUp);
          if (isNaN(parsedDate.getTime())) {
            addMistake('nextFollowUpAt', 'Next follow-up date must be a valid date format (e.g. YYYY-MM-DD)');
          }
        }

        if (rowMistakes.length > 0) {
          rowErrorsMap.set(idx, rowMistakes);
        }
      });
    } else if (dto.entity === 'contacts') {
      if (!headers.includes('name')) {
        errors.push({ row: 1, field: 'name', message: 'Header "name" is required for contacts import' });
      }

      const existingContacts = await this.prisma.contact.findMany({
        where: this.tenant.scopeWhere(ctx),
        select: { email: true, name: true },
      });
      const dbEmails = new Set(existingContacts.map((c) => c.email.toLowerCase().trim()));
      const dbNames = new Set(existingContacts.map((c) => c.name.toLowerCase().trim()));
      const seenEmails = new Set<string>();
      const seenNames = new Set<string>();

      rows.forEach((r, idx) => {
        const rowNum = idx + 2;
        if (!r.name) errors.push({ row: rowNum, field: 'name', message: 'Name cannot be empty' });

        const emailVal = r.email ? r.email.toLowerCase().trim() : null;
        const nameVal = r.name ? r.name.toLowerCase().trim() : null;

        if (emailVal) {
          if (dbEmails.has(emailVal)) {
            errors.push({ row: rowNum, field: 'email', message: `Contact with email "${r.email}" already exists in CRM (Duplicate)` });
          } else if (seenEmails.has(emailVal)) {
            errors.push({ row: rowNum, field: 'email', message: `Email "${r.email}" appears multiple times in import file (Duplicate)` });
          }
          seenEmails.add(emailVal);
        }

        if (nameVal) {
          if (dbNames.has(nameVal)) {
            errors.push({ row: rowNum, field: 'name', message: `Contact "${r.name}" already exists in CRM (Duplicate)` });
          } else if (seenNames.has(nameVal)) {
            errors.push({ row: rowNum, field: 'name', message: `Contact "${r.name}" appears multiple times in import file (Duplicate)` });
          }
          seenNames.add(nameVal);
        }
      });
    } else if (dto.entity === 'accounts') {
      if (!headers.includes('name')) {
        errors.push({ row: 1, field: 'name', message: 'Header "name" is required for accounts import' });
      }

      const existingAccounts = await this.prisma.customer.findMany({
        where: this.tenant.scopeWhere(ctx),
        select: { name: true },
      });
      const dbNames = new Set(existingAccounts.map((a) => a.name.toLowerCase().trim()));
      const seenNames = new Set<string>();

      rows.forEach((r, idx) => {
        const rowNum = idx + 2;
        if (!r.name) errors.push({ row: rowNum, field: 'name', message: 'Name cannot be empty' });

        const nameVal = r.name ? r.name.toLowerCase().trim() : null;
        if (nameVal) {
          if (dbNames.has(nameVal)) {
            errors.push({ row: rowNum, field: 'name', message: `Account "${r.name}" already exists in CRM (Duplicate)` });
          } else if (seenNames.has(nameVal)) {
            errors.push({ row: rowNum, field: 'name', message: `Account "${r.name}" appears multiple times in import file (Duplicate)` });
          }
          seenNames.add(nameVal);
        }
      });
    } else if (dto.entity === 'deals') {
      if (!headers.includes('title')) {
        errors.push({ row: 1, field: 'title', message: 'Header "title" is required for deals import' });
      }

      const existingDeals = await this.prisma.deal.findMany({
        where: this.tenant.scopeWhere(ctx),
        select: { title: true },
      });
      const dbTitles = new Set(existingDeals.map((d) => d.title.toLowerCase().trim()));
      const seenTitles = new Set<string>();

      rows.forEach((r, idx) => {
        const rowNum = idx + 2;
        if (!r.title) errors.push({ row: rowNum, field: 'title', message: 'Title cannot be empty' });

        const titleVal = r.title ? r.title.toLowerCase().trim() : null;
        if (titleVal) {
          if (dbTitles.has(titleVal)) {
            errors.push({ row: rowNum, field: 'title', message: `Deal "${r.title}" already exists in CRM (Duplicate)` });
          } else if (seenTitles.has(titleVal)) {
            errors.push({ row: rowNum, field: 'title', message: `Deal "${r.title}" appears multiple times in import file (Duplicate)` });
          }
          seenTitles.add(titleVal);
        }
      });
    }

    const previewRows = rows.map((r, idx) => {
      const rowErrs = rowErrorsMap.get(idx) || [];
      return {
        ...r,
        _rowNumber: idx + 1,
        _fileLine: idx + 2,
        _isValid: rowErrs.length === 0,
        _errors: rowErrs,
      };
    });

    const errorCount = errors.length;
    const invalidRowIndices = new Set(errors.map((e) => e.row));
    const validCount = Math.max(0, rows.length - invalidRowIndices.size);

    return {
      totalRows: rows.length,
      headers,
      validCount,
      validRows: validCount,
      errorCount,
      sampleRows: previewRows,
      previewRows,
      errors: errors.slice(0, 50),
    };
  }

  // Commits validated CSV records into the tenant database transactionally.
  async commitImport(ctx: RequestTenantContext, dto: ImportCommitDto) {
    const { headers, rows } = parseCsv(dto.csvContent);

    if (rows.length === 0) {
      throw new BadRequestException('CSV content has no rows to import');
    }

    const errors: Array<{ row: number; message: string }> = [];
    let importedCount = 0;

    if (dto.entity === 'leads') {
      const hasName = headers.includes('name');
      const hasService = headers.includes('serviceinterest') || headers.includes('service') || headers.includes('service_interest');

      if (!hasName || !hasService) {
        throw new BadRequestException('Required headers "name" and "serviceInterest" are missing');
      }

      const tenantId = this.tenant.getRequiredTenantId(ctx);
      const [existingLeads, dbServices] = await Promise.all([
        this.prisma.lead.findMany({
          where: this.tenant.scopeWhere(ctx),
          select: { email: true, phone: true },
        }),
        this.prisma.service.findMany({
          where: { tenantId, isActive: true },
          select: { name: true },
        }),
      ]);

      const dbEmails = new Set(existingLeads.filter((l) => l.email).map((l) => l.email.toLowerCase().trim()));
      const dbPhones = new Set(existingLeads.filter((l) => l.phone).map((l) => l.phone!.trim().replace(/[\s\-()]/g, '')));

      const activeServiceNames = dbServices.map((s) => s.name);
      const validServices = activeServiceNames.length > 0 ? activeServiceNames : Array.from(new Set(SERVICE_INTERESTS));
      const validServicesLower = new Map<string, string>();
      validServices.forEach((s) => validServicesLower.set(s.toLowerCase().trim(), s));

      const validSourcesLower = new Map<string, string>();
      LEAD_SOURCES.forEach((s) => validSourcesLower.set(s.toLowerCase().trim(), s));

      const statusMap: Record<string, LeadStatus> = {
        new: LeadStatus.NEW,
        'new enquiry': LeadStatus.NEW,
        contacted: LeadStatus.CONTACTED,
        'follow-up': LeadStatus.CONTACTED,
        'follow up': LeadStatus.CONTACTED,
        'follow-up in progress': LeadStatus.CONTACTED,
        qualified: LeadStatus.QUALIFIED,
        'requirement approved': LeadStatus.QUALIFIED,
        nurturing: LeadStatus.NURTURING,
        discussion: LeadStatus.NURTURING,
        'discussion / demo scheduled': LeadStatus.NURTURING,
        unqualified: LeadStatus.UNQUALIFIED,
        dropped: LeadStatus.UNQUALIFIED,
        'not interested / dropped': LeadStatus.UNQUALIFIED,
      };

      const fileEmails = new Set<string>();
      const filePhones = new Set<string>();
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

      for (let i = 0; i < rows.length; i++) {
        const r = rows[i];
        const tableRowNum = i + 1;
        const excelLineNum = i + 2;
        const name = (r.name || '').trim();
        const email = (r.email || '').trim().toLowerCase();
        const phone = (r.phone || '').trim();
        const rawService = (r.serviceinterest || r.service || r.service_interest || '').trim();
        const rawSource = (r.source || '').trim();
        const rawStatus = (r.status || '').trim().toLowerCase();
        const rawEstValue = (r.estimatedvalue || r.estimated_value || r.value || '').trim().replace(/,/g, '');
        const rawFollowUp = (r.nextfollowupat || r.next_follow_up || r.followup || '').trim();

        if (!name) {
          errors.push({ row: tableRowNum, message: `Row ${tableRowNum} (Excel line ${excelLineNum}): Full name is required` });
          continue;
        }

        if (!email && !phone) {
          errors.push({ row: tableRowNum, message: `Row ${tableRowNum} (Excel line ${excelLineNum}): At least Email or Phone is required` });
          continue;
        }

        if (email && !emailRegex.test(email)) {
          errors.push({ row: tableRowNum, message: `Row ${tableRowNum} (Excel line ${excelLineNum}): Invalid email format "${r.email}"` });
          continue;
        }

        if (phone && !PHONE_PATTERN.test(phone)) {
          errors.push({ row: tableRowNum, message: `Row ${tableRowNum} (Excel line ${excelLineNum}): Invalid phone format "${r.phone}"` });
          continue;
        }

        const normPhone = phone ? phone.replace(/[\s\-()]/g, '') : null;
        if (email && (dbEmails.has(email) || fileEmails.has(email))) {
          errors.push({ row: tableRowNum, message: `Row ${tableRowNum} (Excel line ${excelLineNum}): Skipped duplicate email "${r.email}"` });
          continue;
        }
        if (normPhone && (dbPhones.has(normPhone) || filePhones.has(normPhone))) {
          errors.push({ row: tableRowNum, message: `Row ${tableRowNum} (Excel line ${excelLineNum}): Skipped duplicate phone "${r.phone}"` });
          continue;
        }

        if (!rawService) {
          errors.push({ row: tableRowNum, message: `Row ${tableRowNum} (Excel line ${excelLineNum}): Service interest is mandatory` });
          continue;
        }

        const matchedService = validServicesLower.get(rawService.toLowerCase());
        if (!matchedService) {
          const sampleList = validServices.join(', ');
          errors.push({ row: tableRowNum, message: `Row ${tableRowNum} (Excel line ${excelLineNum}): Service "${rawService}" is not recognized. Active services in catalog: ${sampleList}` });
          continue;
        }

        let matchedSource = 'Website';
        if (rawSource) {
          const isCustomOther = rawSource.toLowerCase().startsWith('other');
          const foundSource = validSourcesLower.get(rawSource.toLowerCase());
          if (!foundSource && !isCustomOther) {
            errors.push({ row: tableRowNum, message: `Row ${tableRowNum} (Excel line ${excelLineNum}): Source "${r.source}" is invalid. Allowed sources: ${LEAD_SOURCES.join(', ')}` });
            continue;
          }
          matchedSource = foundSource || rawSource;
        }

        const matchedStatus = rawStatus ? statusMap[rawStatus] : LeadStatus.NEW;
        if (rawStatus && !matchedStatus) {
          errors.push({ row: tableRowNum, message: `Row ${tableRowNum} (Excel line ${excelLineNum}): Invalid status "${r.status}"` });
          continue;
        }

        const estVal = rawEstValue ? Number(rawEstValue) : 0;
        if (rawEstValue && (isNaN(estVal) || estVal < 0)) {
          errors.push({ row: tableRowNum, message: `Row ${tableRowNum} (Excel line ${excelLineNum}): Estimated value must be a valid non-negative number` });
          continue;
        }

        let parsedFollowUp: Date | null = null;
        if (rawFollowUp) {
          parsedFollowUp = new Date(rawFollowUp);
          if (isNaN(parsedFollowUp.getTime())) {
            errors.push({ row: tableRowNum, message: `Row ${tableRowNum} (Excel line ${excelLineNum}): Invalid next follow-up date` });
            continue;
          }
        }

        try {
          await this.prisma.lead.create({
            data: this.tenant.scopeCreate(ctx, {
              name,
              company: r.company?.trim() || '',
              title: r.title?.trim() || null,
              email: email || '',
              phone: phone || null,
              city: r.city?.trim() || null,
              source: matchedSource,
              serviceInterest: matchedService,
              status: matchedStatus,
              estimatedValue: isNaN(estVal) ? 0 : estVal,
              nextFollowUpAt: parsedFollowUp,
              ownerId: ctx.userId,
            }),
          });
          importedCount++;
          if (email) fileEmails.add(email);
          if (normPhone) filePhones.add(normPhone);
        } catch (err) {
          errors.push({ row: tableRowNum, message: `Row ${tableRowNum} (Excel line ${excelLineNum}): ${(err as Error).message}` });
        }
      }
    } else if (dto.entity === 'contacts') {
      if (!headers.includes('name')) {
        throw new BadRequestException('Required header "name" is missing');
      }

      const existingContacts = await this.prisma.contact.findMany({
        where: this.tenant.scopeWhere(ctx),
        select: { email: true, name: true },
      });
      const dbEmails = new Set(existingContacts.map((c) => c.email.toLowerCase().trim()));
      const dbNames = new Set(existingContacts.map((c) => c.name.toLowerCase().trim()));
      const fileEmails = new Set<string>();
      const fileNames = new Set<string>();

      for (let i = 0; i < rows.length; i++) {
        const r = rows[i];
        const rowNum = i + 2;
        if (!r.name) {
          errors.push({ row: rowNum, message: 'Name is required' });
          continue;
        }

        const email = r.email?.trim() || `${r.name.toLowerCase().replace(/[^a-z0-9]/g, '') || 'contact'}@example.com`;
        const emailKey = email.toLowerCase().trim();
        const nameKey = r.name.toLowerCase().trim();

        if (dbEmails.has(emailKey) || fileEmails.has(emailKey) || dbNames.has(nameKey) || fileNames.has(nameKey)) {
          errors.push({ row: rowNum, message: `Skipped duplicate contact "${r.name}" (${email})` });
          continue;
        }

        try {
          await this.prisma.contact.create({
            data: this.tenant.scopeCreate(ctx, {
              name: r.name,
              email,
              phone: r.phone || null,
              title: r.title || null,
              lifecycle: r.lifecycle || 'Prospect',
              ownerId: ctx.userId,
            }),
          });
          importedCount++;
          fileEmails.add(emailKey);
          fileNames.add(nameKey);
        } catch (err) {
          errors.push({ row: rowNum, message: (err as Error).message });
        }
      }
    } else if (dto.entity === 'accounts') {
      if (!headers.includes('name')) {
        throw new BadRequestException('Required header "name" is missing');
      }

      const existingAccounts = await this.prisma.customer.findMany({
        where: this.tenant.scopeWhere(ctx),
        select: { name: true },
      });
      const dbNames = new Set(existingAccounts.map((a) => a.name.toLowerCase().trim()));
      const fileNames = new Set<string>();

      for (let i = 0; i < rows.length; i++) {
        const r = rows[i];
        const rowNum = i + 2;
        if (!r.name) {
          errors.push({ row: rowNum, message: 'Name is required' });
          continue;
        }

        const nameKey = r.name.toLowerCase().trim();
        if (dbNames.has(nameKey) || fileNames.has(nameKey)) {
          errors.push({ row: rowNum, message: `Skipped duplicate account "${r.name}"` });
          continue;
        }

        try {
          const contactName = r.contactperson || r.contact_person || null;
          const contactEmail = r.email || null;
          await this.prisma.$transaction(async (tx) => {
            const customerNumber = await this.numbering.getNextNumber(this.tenant.getRequiredTenantId(ctx), 'CUSTOMER', 'GLOBAL', tx);
            const account = await tx.customer.create({
              data: this.tenant.scopeCreate(ctx, {
                customerNumber,
                name: r.name,
                industry: r.industry || null,
                city: r.city || null,
                website: r.website || null,
                phone: r.phone || null,
                ownerId: ctx.userId,
              }),
              select: { id: true },
            });
            if (contactName || contactEmail) {
              await tx.contact.create({
                data: this.tenant.scopeCreate(ctx, {
                  accountId: account.id,
                  name: contactName || r.name,
                  email: contactEmail || '',
                  phone: r.phone || null,
                  ownerId: ctx.userId,
                  lifecycle: 'Customer',
                }),
              });
            }
          });
          importedCount++;
          fileNames.add(nameKey);
        } catch (err) {
          errors.push({ row: rowNum, message: (err as Error).message });
        }
      }
    } else if (dto.entity === 'deals') {
      if (!headers.includes('title')) {
        throw new BadRequestException('Required header "title" is missing');
      }

      const tenantId = this.tenant.getRequiredTenantId(ctx);
      let count = await this.prisma.deal.count({ where: { tenantId } });

      const existingDeals = await this.prisma.deal.findMany({
        where: { tenantId },
        select: { title: true },
      });
      const dbTitles = new Set(existingDeals.map((d) => d.title.toLowerCase().trim()));
      const fileTitles = new Set<string>();

      for (let i = 0; i < rows.length; i++) {
        const r = rows[i];
        const rowNum = i + 2;
        if (!r.title) {
          errors.push({ row: rowNum, message: 'Title is required' });
          continue;
        }

        const titleKey = r.title.toLowerCase().trim();
        if (dbTitles.has(titleKey) || fileTitles.has(titleKey)) {
          errors.push({ row: rowNum, message: `Skipped duplicate deal "${r.title}"` });
          continue;
        }

        count++;
        const dealNumber = `DL-${String(count).padStart(4, '0')}`;
        let stage: DealStage = DealStage.QUALIFICATION;
        if (r.stage && Object.values(DealStage).includes(r.stage.toUpperCase() as DealStage)) {
          stage = r.stage.toUpperCase() as DealStage;
        }

        try {
          await this.prisma.deal.create({
            data: this.tenant.scopeCreate(ctx, {
              dealNumber,
              title: r.title,
              amount: Number(r.amount) || 0,
              stage,
              engagementModel: r.engagementmodel || 'Fixed price',
              estimatedHours: Number(r.estimatedhours) || 0,
              ownerId: ctx.userId,
            }),
          });
          importedCount++;
          fileTitles.add(titleKey);
        } catch (err) {
          errors.push({ row: rowNum, message: (err as Error).message });
        }
      }
    }

    return {
      success: importedCount > 0,
      importedCount,
      errors,
    };
  }

  // Returns downloadable Excel template with headers, example records, and validation field guide for entity import.
  async getTemplate(ctxOrEntity: RequestTenantContext | string, maybeEntity?: string) {
    let ctx: RequestTenantContext | undefined;
    let entity: string;

    if (typeof ctxOrEntity === 'string') {
      entity = ctxOrEntity;
      ctx = undefined;
    } else {
      ctx = ctxOrEntity;
      entity = maybeEntity || '';
    }

    let headers: string[] = [];
    let sampleRows: string[][] = [];
    let instructions: string[][] = [];

    switch (entity) {
      case 'leads': {
        headers = ['name', 'company', 'email', 'phone', 'title', 'city', 'serviceInterest', 'source', 'status', 'estimatedValue', 'nextFollowUpAt'];

        let sampleService = 'Web & mobile apps';
        let activeServiceNames: string[] = [];

        if (ctx?.tenantId) {
          try {
            const tenantServices = await this.prisma.service.findMany({
              where: { tenantId: ctx.tenantId, isActive: true },
              select: { name: true },
            });
            if (tenantServices.length > 0) {
              activeServiceNames = tenantServices.map((s) => s.name);
              sampleService = activeServiceNames[0];
            }
          } catch {
            // fallback to default services
          }
        }

        if (activeServiceNames.length === 0) {
          activeServiceNames = [...SERVICE_INTERESTS];
          sampleService = activeServiceNames[0];
        }

        sampleRows = [
          ['Jane Smith', 'Acme Technologies', 'jane.smith@acme.example.com', '+91 98765 43210', 'VP Product', 'Bangalore', sampleService, 'Website', 'New Enquiry', '250000', '2026-12-01 10:00'],
          [
            'Alex Rivera',
            '', // Demonstrates optional company for individual clients
            'alex.rivera@example.com',
            '+91 98765 43211',
            'Consultant',
            'Chennai',
            sampleService,
            'LinkedIn',
            'Follow-up',
            '180000',
            '2026-12-05 14:30',
          ],
        ];

        instructions = [
          ['LEADS IMPORT REFERENCE GUIDE & FIELD VALIDATIONS'],
          [],
          ['Field Name', 'Mandatory / Optional', 'Type & Validation Rules', 'Allowed Values / Examples'],
          ['name', 'MANDATORY', 'Full name of contact person (Max 200 characters)', 'Jane Smith'],
          ['company', 'OPTIONAL', 'Company name. Leave blank for individual clients', 'Acme Technologies or (blank)'],
          ['email', 'MANDATORY*', 'Valid email address format (*Provide at least Email or Phone)', 'jane.smith@acme.example.com'],
          ['phone', 'MANDATORY*', 'Phone number (*Provide at least Email or Phone)', '+91 98765 43210'],
          ['title', 'OPTIONAL', 'Job title or designation (Max 150 characters)', 'VP Product / Director'],
          ['city', 'OPTIONAL', 'City location (Max 100 characters)', 'Bangalore / Chennai / Mumbai'],
          ['serviceInterest', 'MANDATORY', 'Must match an active service in your CRM catalog', activeServiceNames.join(', ')],
          ['source', 'OPTIONAL', 'Lead acquisition channel (Default: Website)', 'Website, Referral, LinkedIn, WhatsApp, etc.'],
          ['status', 'OPTIONAL', 'Initial lead status (Default: New Enquiry)', 'New Enquiry, Follow-up, Qualified, Discussion, Dropped'],
          ['estimatedValue', 'OPTIONAL', 'Expected deal value in INR (Number >= 0)', '250000'],
          ['nextFollowUpAt', 'OPTIONAL', 'Follow-up date/time (YYYY-MM-DD HH:mm)', '2026-12-01 10:00'],
        ];
        break;
      }
      case 'contacts':
        headers = ['name', 'email', 'phone', 'title', 'lifecycle'];
        sampleRows = [
          ['Michael Scott', 'michael.scott@dunder.example.com', '+1 555-0122', 'Regional Manager', 'Customer'],
          ['Pam Beesly', 'pam.beesly@dunder.example.com', '+1 555-0133', 'Office Manager', 'Prospect'],
        ];
        break;
      case 'accounts':
        headers = ['name', 'contactPerson', 'email', 'phone', 'city', 'industry', 'website'];
        sampleRows = [
          ['Acme Global Solutions', 'Ramesh Kumar', 'ramesh@acmeglobal.example.com', '+91 98450 11223', 'Bangalore', 'Software & IT', 'https://acmeglobal.example.com'],
          ['Kaveri Logistics', 'Suresh Babu', 'suresh@kaverilogistics.example.com', '+91 98765 43210', 'Chennai', 'Logistics', 'https://kaveri.example.com'],
        ];
        break;
      case 'deals':
        headers = ['title', 'amount', 'stage', 'engagementModel', 'estimatedHours'];
        sampleRows = [['Cloud ERP Migration', '1500000', 'QUALIFICATION', 'Fixed price', '240']];
        break;
      default:
        throw new BadRequestException(`Template not supported for entity "${entity}"`);
    }

    const csv = [headers.join(','), ...sampleRows.map((r) => r.map(escapeCsvCell).join(','))].join('\n');

    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet(`${entity}_template`);
    worksheet.addRow(headers);
    for (const r of sampleRows) {
      worksheet.addRow(r);
    }

    if (instructions.length > 0) {
      const wsInst = workbook.addWorksheet('Field Guide');
      for (const instRow of instructions) {
        wsInst.addRow(instRow);
      }
    }

    const xlsxBuffer = Buffer.from(await workbook.xlsx.writeBuffer());

    return {
      filename: `${entity}_template.xlsx`,
      buffer: xlsxBuffer,
      csv,
      mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    };
  }
}
