import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { checkDeleteAllowed, markInactive, logAuditEvent, logBlockedDelete } from '@/lib/gfs/guardrails';

export const dynamic = 'force-dynamic';

// GET /api/erp/crm/customers/[id] - Get single customer with full details
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const customer = await prisma.customer.findUnique({
      where: { id: params.id },
      include: {
        contacts: true,
        salesOrders: {
          orderBy: { createdAt: 'desc' },
          take: 10,
          include: { items: true }
        },
        opportunities: {
          orderBy: { createdAt: 'desc' },
          take: 10
        },
        quotes: {
          orderBy: { createdAt: 'desc' },
          take: 5
        },
        leads: true
      }
    });

    if (!customer) {
      return NextResponse.json({ error: 'Customer not found' }, { status: 404 });
    }

    // Calculate lifetime value
    const lifetimeValue = customer.salesOrders
      .filter(o => o.status === 'completed')
      .reduce((sum, o) => sum + (o.total || 0), 0);

    return NextResponse.json({ customer, lifetimeValue });
  } catch (error) {
    console.error('Get customer error:', error);
    return NextResponse.json({ error: 'Failed to fetch customer' }, { status: 500 });
  }
}

// PATCH /api/erp/crm/customers/[id] - Update customer (with audit trail)
export async function PATCH(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const body = await request.json();
    
    // Get previous state for audit
    const before = await prisma.customer.findUnique({ where: { id: params.id } });
    if (!before) {
      return NextResponse.json({ error: 'Customer not found' }, { status: 404 });
    }

    const customer = await prisma.customer.update({
      where: { id: params.id },
      data: body
    });

    // Audit trail
    await logAuditEvent({
      action: 'edit',
      resource: 'customer',
      resourceId: params.id,
      performedBy: 'system',
      reason: body._reason || 'Customer record updated',
      previousState: { name: before.name, status: before.status, email: before.email },
      newState: { name: customer.name, status: customer.status, email: customer.email },
    });

    return NextResponse.json({ customer });
  } catch (error) {
    console.error('Update customer error:', error);
    return NextResponse.json({ error: 'Failed to update customer' }, { status: 500 });
  }
}

// DELETE /api/erp/crm/customers/[id] - GAAP Guardrail-Enforced Delete
// Checks referential integrity before allowing any deletion.
// If customer has history → soft-delete (mark inactive) only.
// If no history → hard delete is safe.
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const guardrail = await checkDeleteAllowed('customer', params.id);

    if (guardrail.action === 'hard_delete') {
      // No linked records — safe to hard delete
      await prisma.customer.delete({ where: { id: params.id } });
      await logAuditEvent({
        action: 'delete',
        resource: 'customer',
        resourceId: params.id,
        performedBy: 'system',
        reason: 'Hard delete — no linked transactions.',
        previousState: { id: params.id },
        newState: {},
      });
      return NextResponse.json({ success: true, action: 'deleted' });
    }

    if (guardrail.action === 'soft_delete') {
      // Has linked records — block hard delete, offer soft delete
      await logBlockedDelete('customer', params.id, 'system', guardrail.reason);
      return NextResponse.json(
        {
          success: false,
          action: 'blocked',
          guardrail: true,
          reason: guardrail.reason,
          hasHistory: true,
          linkedRecords: guardrail.linkedRecords,
          suggestion: 'Use PATCH with { "status": "inactive" } or call /api/erp/crm/customers/[id]/inactivate instead.',
        },
        { status: 409 }
      );
    }

    return NextResponse.json({ error: 'Delete not allowed', reason: guardrail.reason }, { status: 403 });
  } catch (error) {
    console.error('Delete customer error:', error);
    return NextResponse.json({ error: 'Failed to process delete request' }, { status: 500 });
  }
}

// POST /api/erp/crm/customers/[id] with action=inactivate — Mark Inactive
export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const body = await request.json();
    
    if (body.action === 'inactivate') {
      const result = await markInactive(
        'customer',
        params.id,
        body.performedBy || 'system',
        body.reason || 'Marked inactive by operator'
      );
      if (!result.success) {
        return NextResponse.json({ error: result.error }, { status: 400 });
      }
      return NextResponse.json({ success: true, action: 'inactivated' });
    }

    if (body.action === 'reactivate') {
      await prisma.customer.update({
        where: { id: params.id },
        data: { status: 'active' },
      });
      await logAuditEvent({
        action: 'reactivate',
        resource: 'customer',
        resourceId: params.id,
        performedBy: body.performedBy || 'system',
        reason: body.reason || 'Reactivated by operator',
        previousState: { status: 'inactive' },
        newState: { status: 'active' },
      });
      return NextResponse.json({ success: true, action: 'reactivated' });
    }

    return NextResponse.json({ error: 'Unknown action' }, { status: 400 });
  } catch (error) {
    console.error('Customer action error:', error);
    return NextResponse.json({ error: 'Failed to process action' }, { status: 500 });
  }
}
