import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { LeadStatus, Prisma, UserRole } from '@prisma/client';
import PDFDocument from 'pdfkit';
import { PrismaService } from '../../prisma/prisma.service';
import { RequestTenantContext, TenantQueryHelper } from '../../common/tenancy/tenant-query.helper';
import { assertCanDelete, assertTenantOwner, createEntityNote, listEntityNotes } from '../../common/crm/crm-record.helper';
import { CustomersService as AccountsService } from '../customers/customers.service';
import { DealsService } from '../deals/deals.service';
import { CreateLeadDto } from './dto/create-lead.dto';
import { UpdateLeadDto } from './dto/update-lead.dto';
import { ListLeadsQuery } from './dto/list-leads.query';
import { ConvertLeadDto } from './dto/convert-lead.dto';
import { CreateNoteDto } from './dto/create-note.dto';
import { LEAD_SOURCES, SERVICE_INTERESTS, LeadView } from './lead.constants';

const WEEK_MS = 7 * 24 * 60 * 60 * 1000;
const NOT_FOUND = 'Lead not found';

const leadSelect = {
  id: true,
  name: true,
  company: true,
  title: true,
  email: true,
  phone: true,
  city: true,
  source: true,
  serviceInterest: true,
  status: true,
  estimatedValue: true,
  convertedAccountId: true,
  convertedContactId: true,
  convertedDealId: true,
  convertedAt: true,
  nextFollowUpAt: true,
  createdAt: true,
  updatedAt: true,
  owner: { select: { id: true, name: true } },
  convertedAccount: { select: { id: true, name: true, customerNumber: true } },
  convertedContact: { select: { id: true, name: true } },
  convertedDeal: {
    select: {
      id: true,
      dealNumber: true,
      title: true,
      stage: true,
      amount: true,
    },
  },
} satisfies Prisma.LeadSelect;

type LeadRow = Prisma.LeadGetPayload<{ select: typeof leadSelect }>;
export type LeadDto = Omit<LeadRow, 'estimatedValue' | 'convertedDeal'> & {
  estimatedValue: number;
  convertedDeal: {
    id: string;
    dealNumber: string;
    title: string;
    stage: string;
    amount: number;
  } | null;
};
export type LeadCounts = Record<LeadView, number>;

/** Who is acting, as attached by JwtAuthGuard (request.user). */
export interface LeadActor {
  id: string;
  role: UserRole;
  canDelete: boolean;
}

export type LeadFilters = Partial<Pick<ListLeadsQuery, 'view' | 'status' | 'source' | 'serviceInterest' | 'ownerId' | 'followUp' | 'createdFrom' | 'createdTo' | 'q'>>;

@Injectable()
export class LeadsService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly tenant: TenantQueryHelper,
    private readonly deals: DealsService,
    private readonly accounts: AccountsService,
  ) {}

  // Builds tenant-scoped query filter for lead tab views.
  private viewWhere(view: LeadView, userId: string): Prisma.LeadWhereInput {
    switch (view) {
      case 'all':
        return {};
      case 'mine':
        return { ownerId: userId };
      case 'new':
        return { createdAt: { gte: new Date(Date.now() - WEEK_MS) } };
      case 'converted':
        return { status: LeadStatus.CONVERTED };
      default:
        return {};
    }
  }

  // Maps database lead record to LeadDto with numeric fields.
  private toDto(row: LeadRow): LeadDto {
    return {
      ...row,
      estimatedValue: Number(row.estimatedValue),
      convertedDeal: row.convertedDeal ? { ...row.convertedDeal, amount: Number(row.convertedDeal.amount) } : null,
    };
  }

  // Finds a lead within tenant scope or throws NotFoundException.
  private async findOrThrow(ctx: RequestTenantContext, id: string) {
    const lead = await this.prisma.lead.findFirst({
      where: this.tenant.scopeWhere(ctx, { id }),
      select: {
        id: true,
        name: true,
        company: true,
        title: true,
        email: true,
        phone: true,
        city: true,
        serviceInterest: true,
        estimatedValue: true,
        status: true,
        ownerId: true,
        convertedContactId: true,
      },
    });
    if (!lead) throw new NotFoundException(NOT_FOUND);
    return lead;
  }

  // Returns lead counts for all preset views within tenant scope.
  async counts(ctx: RequestTenantContext): Promise<LeadCounts> {
    const views: LeadView[] = ['all', 'mine', 'new', 'converted'];
    const values = await Promise.all(
      views.map((v) =>
        this.prisma.lead.count({
          where: this.tenant.scopeWhere(ctx, this.viewWhere(v, ctx.userId)),
        }),
      ),
    );
    return Object.fromEntries(views.map((v, i) => [v, values[i]])) as LeadCounts;
  }

  /** Builds the tenant-scoped lead filter shared by the list and the export, so both always return the same rows. */
  filterWhere(ctx: RequestTenantContext, q: LeadFilters): Prisma.LeadWhereInput {
    const now = new Date();
    const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const endOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999);

    const dayOfWeek = (now.getDay() + 6) % 7; // Monday = 0
    const startOfWeek = new Date(startOfToday.getTime() - dayOfWeek * 86400000);
    const endOfWeek = new Date(startOfWeek.getTime() + 7 * 86400000 - 1);

    let followUpWhere: Prisma.LeadWhereInput = {};
    if (q.followUp === 'overdue') {
      followUpWhere = { nextFollowUpAt: { lt: startOfToday } };
    } else if (q.followUp === 'today') {
      followUpWhere = { nextFollowUpAt: { gte: startOfToday, lte: endOfToday } };
    } else if (q.followUp === 'this_week') {
      followUpWhere = { nextFollowUpAt: { gte: startOfWeek, lte: endOfWeek } };
    } else if (q.followUp === 'upcoming') {
      followUpWhere = { nextFollowUpAt: { gt: endOfToday } };
    }

    let dateWhere: Prisma.LeadWhereInput = {};
    if (q.createdFrom || q.createdTo) {
      dateWhere = {
        createdAt: {
          ...(q.createdFrom ? { gte: new Date(q.createdFrom) } : {}),
          ...(q.createdTo ? { lte: new Date(q.createdTo) } : {}),
        },
      };
    }

    const search = q.q ? q.q.replace(/[\\%_]/g, (c) => `\\${c}`) : '';
    return this.tenant.scopeWhere(ctx, {
      AND: [
        this.viewWhere(q.view ?? 'all', ctx.userId),
        q.status ? { status: q.status } : {},
        q.source === 'Other' ? { OR: [{ source: 'Other' }, { source: { startsWith: 'Other:' } }] } : q.source ? { source: q.source } : {},
        q.serviceInterest ? { serviceInterest: q.serviceInterest } : {},
        q.ownerId ? { ownerId: q.ownerId } : {},
        followUpWhere,
        dateWhere,
        search
          ? {
              OR: [{ name: { contains: search } }, { company: { contains: search } }, { email: { contains: search } }, { phone: { contains: search } }, { city: { contains: search } }, { source: { contains: search } }, { serviceInterest: { contains: search } }],
            }
          : {},
      ],
    } satisfies Prisma.LeadWhereInput);
  }

  // Returns paginated leads matching filters, search queries, and sorting.
  async list(ctx: RequestTenantContext, q: ListLeadsQuery) {
    const where = this.filterWhere(ctx, q);

    const orderBy: Prisma.LeadOrderByWithRelationInput[] = [q.sort === 'owner' ? { owner: { name: q.dir } } : { [q.sort]: q.dir }, { id: 'asc' }];

    const [total, rows, counts] = await Promise.all([
      this.prisma.lead.count({ where }),
      this.prisma.lead.findMany({
        where,
        orderBy,
        skip: (q.page - 1) * q.pageSize,
        take: q.pageSize,
        select: leadSelect,
      }),
      this.counts(ctx),
    ]);

    return {
      items: rows.map((r) => this.toDto(r)),
      total,
      page: q.page,
      pageSize: q.pageSize,
      counts,
    };
  }

  // Retrieves single lead details by ID within tenant scope.
  async get(ctx: RequestTenantContext, id: string): Promise<LeadDto> {
    const row = await this.prisma.lead.findFirst({
      where: this.tenant.scopeWhere(ctx, { id }),
      select: leadSelect,
    });
    if (!row) throw new NotFoundException(NOT_FOUND);
    return this.toDto(row);
  }

  // Generates an executive PDF dossier for a single lead.
  async generatePdf(ctx: RequestTenantContext, id: string): Promise<{ filename: string; buffer: Buffer }> {
    const where = this.tenant.scopeWhere(ctx, { id });
    const [lead, org, notes] = await Promise.all([
      this.prisma.lead.findFirst({
        where,
        select: leadSelect,
      }),
      ctx.tenantId
        ? this.prisma.organization.findUnique({
            where: { id: ctx.tenantId },
            select: { name: true },
          })
        : Promise.resolve(null),
      this.listNotes(ctx, id),
    ]);

    if (!lead) throw new NotFoundException(NOT_FOUND);

    const orgName = org?.name || 'TechCMantix CRM';
    const statusLabel: Record<string, string> = {
      NEW: 'New Enquiry',
      CONTACTED: 'Follow-up',
      QUALIFIED: 'Qualified',
      NURTURING: 'Discussion',
      UNQUALIFIED: 'Dropped',
      CONVERTED: 'Converted',
    };

    const doc = new PDFDocument({ size: 'A4', margin: 40, bufferPages: true });
    const buffers: Buffer[] = [];
    doc.on('data', (chunk) => buffers.push(chunk));

    // Top Dark Navy Brand Header
    doc.save();
    doc.rect(40, 40, 515, 50).fill('#0f172a');
    doc.fillColor('#ffffff').fontSize(15).font('Helvetica-Bold').text(orgName.toUpperCase(), 55, 52);
    doc.fontSize(8.5).font('Helvetica').fillColor('#94a3b8').text('EXECUTIVE LEAD DOSSIER', 55, 70);

    const dateStr = new Date().toLocaleDateString('en-IN', {
      day: '2-digit',
      month: 'short',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
    doc.fontSize(8).font('Helvetica').fillColor('#cbd5e1').text(`Generated: ${dateStr}`, 360, 54, { align: 'right', width: 180 });
    doc.text(`Lead ID: ${lead.id.slice(0, 8)}`, 360, 70, { align: 'right', width: 180 });
    doc.restore();

    // Lead Title Card
    let y = 105;
    doc.save();
    doc.rect(40, y, 515, 60).fill('#f8fafc');
    doc.strokeColor('#e2e8f0').lineWidth(1).rect(40, y, 515, 60).stroke();

    doc
      .fillColor('#0f172a')
      .fontSize(16)
      .font('Helvetica-Bold')
      .text(lead.name, 55, y + 12);
    const sub = [lead.title, lead.company].filter(Boolean).join(' at ');
    doc
      .fontSize(10)
      .font('Helvetica')
      .fillColor('#64748b')
      .text(sub || 'Individual Prospect', 55, y + 33);

    // Status pill
    const stText = statusLabel[lead.status] || lead.status;
    doc.rect(420, y + 16, 120, 24).fill('#e0f2fe');
    doc
      .strokeColor('#0284c7')
      .lineWidth(0.5)
      .rect(420, y + 16, 120, 24)
      .stroke();
    doc
      .fillColor('#0369a1')
      .fontSize(8.5)
      .font('Helvetica-Bold')
      .text(stText.toUpperCase(), 420, y + 23, { align: 'center', width: 120 });
    doc.restore();

    y += 75;

    // 2-Column Info Grid: Left = Contact Info, Right = Commercial Scope
    const cardWidth = 250;
    const cardHeight = 150;

    // Left Card: Contact Information
    doc.save();
    doc.rect(40, y, cardWidth, cardHeight).fill('#ffffff');
    doc.strokeColor('#e2e8f0').lineWidth(1).rect(40, y, cardWidth, cardHeight).stroke();
    doc.rect(40, y, cardWidth, 26).fill('#f1f5f9');
    doc
      .fillColor('#1e293b')
      .fontSize(9.5)
      .font('Helvetica-Bold')
      .text('CONTACT DETAILS', 50, y + 8);

    let rowY = y + 36;
    const renderRow = (x: number, label: string, val: string) => {
      doc
        .fillColor('#64748b')
        .fontSize(8.5)
        .font('Helvetica-Bold')
        .text(label, x + 10, rowY, { width: 80 });
      doc
        .fillColor('#0f172a')
        .fontSize(8.5)
        .font('Helvetica')
        .text(val, x + 90, rowY, { width: cardWidth - 100 });
      rowY += 22;
    };

    renderRow(40, 'Email:', lead.email || '—');
    renderRow(40, 'Phone:', lead.phone || '—');
    renderRow(40, 'City:', lead.city || '—');
    renderRow(40, 'Added:', new Date(lead.createdAt).toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' }));
    doc.restore();

    // Right Card: Commercials & Scope
    doc.save();
    const rightX = 305;
    doc.rect(rightX, y, cardWidth, cardHeight).fill('#ffffff');
    doc.strokeColor('#e2e8f0').lineWidth(1).rect(rightX, y, cardWidth, cardHeight).stroke();
    doc.rect(rightX, y, cardWidth, 26).fill('#f1f5f9');
    doc
      .fillColor('#1e293b')
      .fontSize(9.5)
      .font('Helvetica-Bold')
      .text('COMMERCIALS & SCOPE', rightX + 10, y + 8);

    rowY = y + 36;
    const estValStr = lead.estimatedValue ? `INR ${Number(lead.estimatedValue).toLocaleString('en-IN')}` : '—';
    const followUpStr = lead.nextFollowUpAt ? new Date(lead.nextFollowUpAt).toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' }) : 'Not scheduled';

    renderRow(rightX, 'Service:', lead.serviceInterest || '—');
    renderRow(rightX, 'Source:', lead.source || '—');
    renderRow(rightX, 'Est. Value:', estValStr);
    renderRow(rightX, 'Owner:', lead.owner?.name || 'Unassigned');
    renderRow(rightX, 'Follow-up:', followUpStr);
    doc.restore();

    y += cardHeight + 15;

    // Recent Notes / Activity Section
    if (notes.length > 0) {
      doc.save();
      doc.rect(40, y, 515, 24).fill('#0f172a');
      doc
        .fillColor('#ffffff')
        .fontSize(9.5)
        .font('Helvetica-Bold')
        .text(`RECENT ACTIVITY & NOTES (${notes.length})`, 50, y + 7);
      y += 24;

      notes.forEach((note, idx) => {
        const isEven = idx % 2 === 0;
        const noteDate = new Date(note.createdAt).toLocaleDateString('en-IN', {
          day: '2-digit',
          month: 'short',
          year: 'numeric',
          hour: '2-digit',
          minute: '2-digit',
        });

        doc.rect(40, y, 515, 36).fill(isEven ? '#ffffff' : '#f8fafc');
        doc.strokeColor('#e2e8f0').lineWidth(0.5).rect(40, y, 515, 36).stroke();

        doc
          .fillColor('#2563eb')
          .fontSize(8)
          .font('Helvetica-Bold')
          .text(note.author?.name || 'Team member', 50, y + 6);
        doc
          .fillColor('#94a3b8')
          .fontSize(7.5)
          .font('Helvetica')
          .text(` · ${noteDate}`, 130, y + 6.5);
        doc
          .fillColor('#334155')
          .fontSize(8.5)
          .font('Helvetica')
          .text(note.body, 50, y + 18, { width: 495, lineBreak: false, ellipsis: true });
        y += 36;
      });
      doc.restore();
    }

    // Footer on all pages cleanly without page overflow
    const range = doc.bufferedPageRange();
    for (let i = range.start; i < range.start + range.count; i++) {
      doc.switchToPage(i);
      doc.save();
      doc.page.margins.bottom = 0;
      const pageBottom = 770;
      doc.strokeColor('#e2e8f0').lineWidth(1).moveTo(40, pageBottom).lineTo(555, pageBottom).stroke();
      doc
        .fillColor('#94a3b8')
        .fontSize(7.5)
        .font('Helvetica')
        .text('Confidential — For Internal CRM & Sales Use Only', 40, pageBottom + 6, { lineBreak: false });
      doc.text(orgName, 355, pageBottom + 6, { align: 'right', width: 200, lineBreak: false });
      doc.restore();
    }

    doc.end();

    const pdfBuffer = await new Promise<Buffer>((resolve, reject) => {
      doc.on('end', () => resolve(Buffer.concat(buffers)));
      doc.on('error', reject);
    });

    const safeName = lead.name
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/(^-|-$)/g, '');
    return {
      filename: `lead-${safeName || 'dossier'}.pdf`,
      buffer: pdfBuffer,
    };
  }

  // Creates a new lead record within the tenant.
  async create(ctx: RequestTenantContext, dto: CreateLeadDto): Promise<LeadDto> {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const ownerId = dto.ownerId === undefined ? ctx.userId : dto.ownerId;
    await assertTenantOwner(this.prisma, tenantId, ownerId);
    await this.validateSourceAndService(tenantId, dto.source, dto.serviceInterest);

    const cleanEmail = dto.email?.trim() || null;
    const cleanPhone = dto.phone?.trim() || null;
    if (!cleanEmail && !cleanPhone) {
      throw new BadRequestException('At least Email or Phone number is required to create a lead');
    }

    const duplicateOr: Prisma.LeadWhereInput[] = [];
    if (cleanEmail) duplicateOr.push({ email: cleanEmail });
    if (cleanPhone) duplicateOr.push({ phone: cleanPhone });

    const duplicate = await this.prisma.lead.findFirst({
      where: {
        tenantId,
        status: { not: LeadStatus.CONVERTED },
        OR: duplicateOr,
      },
    });

    if (duplicate) {
      throw new ConflictException(duplicate.email === cleanEmail && cleanEmail ? `A lead with email "${cleanEmail}" already exists` : `A lead with phone number "${cleanPhone}" already exists`);
    }

    const row = await this.prisma.lead.create({
      data: this.tenant.scopeCreate(ctx, {
        ...dto,
        company: dto.company?.trim() || '',
        email: cleanEmail || '',
        phone: cleanPhone,
        ownerId,
        status: dto.status ?? LeadStatus.NEW,
        nextFollowUpAt: dto.nextFollowUpAt ? new Date(dto.nextFollowUpAt) : null,
      }),
      select: leadSelect,
    });
    return this.toDto(row);
  }

  // Updates an existing lead record within the tenant.
  async update(ctx: RequestTenantContext, id: string, dto: UpdateLeadDto): Promise<LeadDto> {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const existing = await this.findOrThrow(ctx, id);
    if (existing.status === LeadStatus.CONVERTED && dto.status) {
      throw new BadRequestException('A converted lead keeps its status');
    }
    await assertTenantOwner(this.prisma, tenantId, dto.ownerId);
    const changedService = dto.serviceInterest !== existing.serviceInterest ? dto.serviceInterest : undefined;
    if (dto.serviceInterest === null) throw new BadRequestException('Select a service');
    await this.validateSourceAndService(tenantId, dto.source, changedService);

    const cleanEmail = dto.email !== undefined ? dto.email?.trim() || null : undefined;
    const cleanPhone = dto.phone !== undefined ? dto.phone?.trim() || null : undefined;

    const targetEmail = cleanEmail !== undefined ? cleanEmail : existing.email || null;
    const targetPhone = cleanPhone !== undefined ? cleanPhone : existing.phone || null;
    if (!targetEmail && !targetPhone) {
      throw new BadRequestException('At least Email or Phone number is required for a lead');
    }

    if (cleanEmail || cleanPhone) {
      const duplicateOr: Prisma.LeadWhereInput[] = [];
      if (cleanEmail) duplicateOr.push({ email: cleanEmail });
      if (cleanPhone) duplicateOr.push({ phone: cleanPhone });

      const duplicate = await this.prisma.lead.findFirst({
        where: {
          tenantId,
          id: { not: id },
          status: { not: LeadStatus.CONVERTED },
          OR: duplicateOr,
        },
      });

      if (duplicate) {
        throw new ConflictException(duplicate.email === cleanEmail && cleanEmail ? `A lead with email "${cleanEmail}" already exists` : `A lead with phone number "${cleanPhone}" already exists`);
      }
    }

    const { email, phone, company, nextFollowUpAt, ...rest } = dto;
    const updateData: Prisma.LeadUncheckedUpdateManyInput = {
      ...rest,
      ...(email !== undefined ? { email: cleanEmail || '' } : {}),
      ...(phone !== undefined ? { phone: cleanPhone } : {}),
      ...(company !== undefined ? { company: company?.trim() || '' } : {}),
      ...(nextFollowUpAt !== undefined ? { nextFollowUpAt: nextFollowUpAt ? new Date(nextFollowUpAt) : null } : {}),
    };

    await this.prisma.lead.updateMany({
      where: this.tenant.scopeWhere(ctx, { id }),
      data: updateData,
    });
    return this.get(ctx, id);
  }

  // Deletes a lead record if the actor has deletion permissions.
  async remove(ctx: RequestTenantContext, actor: LeadActor, id: string) {
    await this.findOrThrow(ctx, id);
    assertCanDelete(actor);
    await this.prisma.lead.deleteMany({
      where: this.tenant.scopeWhere(ctx, { id }),
    });
    return { id };
  }

  // Converts a lead into a customer (new or existing), a contact and an optional deal in one transaction, using the reviewed form values when given.
  async convert(ctx: RequestTenantContext, id: string, dto: ConvertLeadDto = {}) {
    const lead = await this.findOrThrow(ctx, id);
    if (lead.status === LeadStatus.CONVERTED || lead.convertedContactId) {
      throw new BadRequestException('Lead is already converted');
    }
    if (lead.status === LeadStatus.UNQUALIFIED) {
      throw new BadRequestException('Dropped leads cannot be converted to customer');
    }

    const form = dto.customer;
    if (form?.ownerId) await assertTenantOwner(this.prisma, this.tenant.getRequiredTenantId(ctx), form.ownerId);
    if (dto.accountId) {
      const explicitAccount = await this.prisma.customer.findFirst({
        where: this.tenant.scopeWhere(ctx, { id: dto.accountId }),
        select: { id: true },
      });
      if (!explicitAccount) throw new NotFoundException('Account not found');
    }

    const now = new Date();
    const ownerId = lead.ownerId ?? ctx.userId;

    return this.prisma.$transaction(async (tx) => {
      // Atomic lock inside transaction preventing duplicate conversions
      const lockRes = await tx.lead.updateMany({
        where: this.tenant.scopeWhere(ctx, {
          id,
          status: { notIn: [LeadStatus.CONVERTED, LeadStatus.UNQUALIFIED] },
          convertedContactId: null,
        }),
        data: {
          status: LeadStatus.CONVERTED,
          convertedAt: now,
        },
      });

      if (lockRes.count === 0) {
        throw new BadRequestException('This lead was already converted or dropped');
      }

      const accountName = form?.name || lead.company?.trim() || lead.name;
      const accountSelect = { id: true, name: true, customerNumber: true } as const;
      let account = dto.accountId ? await tx.customer.findFirst({ where: this.tenant.scopeWhere(ctx, { id: dto.accountId }), select: accountSelect }) : dto.newAccount ? null : await tx.customer.findFirst({ where: this.tenant.scopeWhere(ctx, { name: accountName }), select: accountSelect });

      const reusedAccount = Boolean(account);
      if (!account) {
        account = await this.accounts.createInTransaction(tx, ctx, {
          name: accountName,
          city: form ? (form.city ?? null) : lead.city || null,
          phone: form ? (form.phone ?? null) : lead.phone || null,
          industry: form?.industry ?? null,
          website: form?.website ?? null,
          techStack: form?.techStack ?? null,
          ownerId: form?.ownerId ?? ownerId,
        });
      }

      if (!account) {
        throw new BadRequestException('Customer record is required');
      }

      const contact = await tx.contact.create({
        data: this.tenant.scopeCreate(ctx, {
          name: form?.contactPerson || lead.name,
          accountId: account.id,
          title: form?.contactTitle !== undefined ? form.contactTitle : lead.title,
          email: form?.email || lead.email || '',
          phone: lead.phone || form?.phone || null,
          ownerId,
          lifecycle: dto.lifecycle ?? 'Prospect',
          lastActivityAt: now,
        }),
        select: { id: true, name: true, email: true, accountId: true },
      });

      const shouldCreateDeal = dto.createDeal !== false;
      const defaultCloseDate = new Date(now.getTime() + 45 * 86400000);
      const leadEst = Number(lead.estimatedValue) || 0;
      const deal = shouldCreateDeal
        ? await this.deals.createInTransaction(tx, ctx, {
            title: dto.dealTitle || (lead.serviceInterest ? `${account.name} — ${lead.serviceInterest}` : `${account.name} — New business`),
            accountId: account.id,
            contactId: contact.id,
            amount: dto.dealAmount !== undefined ? dto.dealAmount : leadEst,
            closeDate: dto.closeDate ? new Date(dto.closeDate) : defaultCloseDate,
            engagementModel: dto.engagementModel ?? null,
            estimatedHours: dto.estimatedHours ?? null,
            ownerId,
          })
        : null;

      await tx.lead.updateMany({
        where: this.tenant.scopeWhere(ctx, { id }),
        data: {
          convertedAccountId: account.id,
          convertedContactId: contact.id,
          convertedDealId: deal?.id ?? null,
          nextFollowUpAt: null,
        },
      });

      const customerLabel = [account.name, account.customerNumber].filter(Boolean).join(' · ');
      await createEntityNote(tx, this.tenant, ctx, 'leadId', id, `Converted to customer ${customerLabel}${deal ? ` with deal ${deal.dealNumber}` : ''}.`);
      await createEntityNote(tx, this.tenant, ctx, 'accountId', account.id, `${reusedAccount ? 'Contact added' : 'Customer created'} from lead ${lead.name}${deal ? ` with deal ${deal.dealNumber}` : ''}.`);

      const updatedLead = await tx.lead.findFirst({
        where: this.tenant.scopeWhere(ctx, { id }),
        select: leadSelect,
      });

      return {
        lead: updatedLead ? this.toDto(updatedLead) : null,
        account,
        contact,
        deal,
        reusedAccount,
      };
    });
  }

  // Returns all notes attached to the lead.
  async listNotes(ctx: RequestTenantContext, id: string) {
    await this.findOrThrow(ctx, id);
    return listEntityNotes(this.prisma, this.tenant, ctx, 'leadId', id);
  }

  // Creates and attaches a new note to the lead.
  async addNote(ctx: RequestTenantContext, id: string, dto: CreateNoteDto) {
    await this.findOrThrow(ctx, id);
    return createEntityNote(this.prisma, this.tenant, ctx, 'leadId', id, dto.body);
  }

  /** Accepts a listed source or "Other: <text>", and a service that is active in the tenant's Services list. */
  private async validateSourceAndService(tenantId: string, source?: string | null, serviceInterest?: string | null) {
    if (source) {
      const isKnown = (LEAD_SOURCES as readonly string[]).includes(source);
      const isCustomOther = source === 'Other' || /^Other: \S/.test(source);
      if (!isKnown && !isCustomOther) {
        throw new BadRequestException('Choose a source from the list');
      }
    }

    if (serviceInterest) {
      const [found, total] = await Promise.all([this.prisma.service.findFirst({ where: { tenantId, name: serviceInterest, isActive: true }, select: { id: true } }), this.prisma.service.count({ where: { tenantId } })]);
      const builtInFallback = total === 0 && (SERVICE_INTERESTS as readonly string[]).includes(serviceInterest);
      if (!found && !builtInFallback) {
        throw new BadRequestException('Choose a service from the list');
      }
    }
  }
}
