import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditDelete, auditUpdate } from '@/features/foundation/audit-log/service';
import {
  getCustomerActivity,
  getCustomerDetail,
  softDeleteCustomer,
  updateCustomer
} from '@/features/crm/customers/server/service';
import { customerSchema } from '@/features/crm/customers/schemas/customer.schema';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

type Params = {
  params: Promise<{ id: string }>;
};

const customerRequestSchema = customerSchema.extend({
  branchId: z.string().nullable().optional(),
  leadChannel: z.string().nullable().optional(),
  customerGroup: z.string().nullable().optional(),
  customerSubGroup: z.string().nullable().optional()
});

export async function GET(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmCustomerRead
    });
    const [customer, activity] = await Promise.all([
      getCustomerDetail(id, organization.id),
      getCustomerActivity(id, organization.id)
    ]);

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Customer loaded successfully',
      customer,
      activity
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    console.error('GET /api/crm/customers/[id] failed', error);

    return NextResponse.json({ message: 'Unable to load customer' }, { status: 500 });
  }
}

export async function PATCH(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmCustomerUpdate
    });
    const payload = customerRequestSchema.parse(await request.json());
    const before = await getCustomerDetail(id, organization.id);
    const updated = await updateCustomer(id, organization.id, session.user.id, payload);

    await auditUpdate({
      organizationId: organization.id,
      branchId: updated.branchId,
      userId: session.user.id,
      entityType: 'crm_customer',
      entityId: id,
      beforeData: before,
      afterData: updated
    });

    return NextResponse.json({
      success: true,
      message: 'Customer updated successfully',
      customer: updated
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { message: error.issues[0]?.message ?? 'Invalid payload' },
        { status: 400 }
      );
    }

    console.error('PATCH /api/crm/customers/[id] failed', error);

    return NextResponse.json({ message: 'Unable to update customer' }, { status: 500 });
  }
}

export async function DELETE(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmCustomerDelete
    });
    const before = await getCustomerDetail(id, organization.id);
    const updated = await softDeleteCustomer(id, organization.id, session.user.id);

    await auditDelete({
      organizationId: organization.id,
      branchId: updated.branchId,
      userId: session.user.id,
      entityType: 'crm_customer',
      entityId: id,
      beforeData: before,
      afterData: updated
    });

    return NextResponse.json({
      success: true,
      message: 'Customer deleted successfully'
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    console.error('DELETE /api/crm/customers/[id] failed', error);

    return NextResponse.json({ message: 'Unable to delete customer' }, { status: 500 });
  }
}
