/**
 * Lead-to-Customer conversion query — wave-8 leaf5.
 *
 * convertLeadToCustomer:
 *   1. Creates a new customer record from the lead data.
 *   2. Links the lead to the customer (sets customer_id).
 *   3. Logs a 'converted' activity on the lead.
 *   4. Writes audit log entries for both customer create + lead convert.
 *
 * All four writes run in a single transaction.
 *
 * Routes import via @zync/db/queries (barrel) — never directly from here.
 */
import type { Db } from '../client'
import { auditLog } from './_audit-forward'
import { leads, leadActivities } from '../schema/marketing'
import { customers } from '../schema/customers'
import { and, eq } from 'drizzle-orm'

export interface ConvertLeadResult {
  customerId: string
  leadId: string
  customerName: string
}

export interface ConvertLeadCustomerData {
  name: string
  email?: string | null
  phone?: string | null
  company?: string | null
}

export async function convertLeadToCustomer(
  db: Db,
  tenantId: string,
  userId: string,
  leadId: string,
  customerData: ConvertLeadCustomerData,
): Promise<ConvertLeadResult> {
  return db.transaction(async (tx) => {
    // 1. Verify lead exists, is WON, not yet converted
    const [lead] = await tx
      .select()
      .from(leads)
      .where(and(eq(leads.tenantId, tenantId), eq(leads.id, leadId)))
      .limit(1)

    if (!lead) throw new Error('Lead not found')
    if (lead.stage !== 'WON') throw new Error('Only WON leads can be converted to customers')
    if (lead.customerId) throw new Error('Lead already converted to a customer')

    // 2. Create customer record
    const [customer] = await tx
      .insert(customers)
      .values({
        tenantId,
        name: customerData.name,
        email: customerData.email ?? null,
        phone: customerData.phone ?? null,
        company: customerData.company ?? null,
        address: null,
        notes: null,
        status: 'active',
      })
      .returning()

    if (!customer) throw new Error('Failed to create customer')

    // 3. Link lead to the new customer
    await tx
      .update(leads)
      .set({ customerId: customer.id, updatedAt: new Date() })
      .where(and(eq(leads.tenantId, tenantId), eq(leads.id, leadId)))

    // 4. Log 'converted' activity on the lead
    await tx.insert(leadActivities).values({
      tenantId,
      leadId,
      userId,
      type: 'converted',
      content: `Lead converted to customer "${customer.name}"`,
      metadata: { customerId: customer.id },
    })

    // 5. Audit log — customer created
    await tx.insert(auditLog).values({
      tenantId,
      actorId: userId,
      actorType: 'user',
      entityType: 'customer',
      entityId: customer.id,
      action: 'customer.created',
      changes: null,
    })

    // 6. Audit log — lead converted
    await tx.insert(auditLog).values({
      tenantId,
      actorId: userId,
      actorType: 'user',
      entityType: 'lead',
      entityId: leadId,
      action: 'lead.converted',
      changes: { customerId: [null, customer.id] },
    })

    return {
      customerId: customer.id,
      leadId,
      customerName: customer.name,
    }
  })
}
