import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditDelete, auditUpdate } from '@/features/foundation/audit-log/service';
import {
  listCustomerContacts,
  softDeleteCustomerContact,
  updateCustomerContact
} from '@/features/crm/customers/server/service';
import { customerContactSchema } 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; contactId: string }>;
};

export async function PATCH(request: NextRequest, { params }: Params) {
  try {
    const { id, contactId } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmContactUpdate
    });
    const payload = customerContactSchema.parse(await request.json());
    const before = (await listCustomerContacts(id, organization.id)).find(
      (contact) => contact.id === contactId
    );

    if (!before) {
      return NextResponse.json({ message: 'Contact not found' }, { status: 404 });
    }

    const updated = await updateCustomerContact(
      id,
      contactId,
      organization.id,
      session.user.id,
      payload
    );

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

    return NextResponse.json({
      success: true,
      message: 'Contact updated successfully',
      contact: 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 }
      );
    }

    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

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

export async function DELETE(_request: NextRequest, { params }: Params) {
  try {
    const { id, contactId } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmContactDelete
    });
    const before = (await listCustomerContacts(id, organization.id)).find(
      (contact) => contact.id === contactId
    );

    if (!before) {
      return NextResponse.json({ message: 'Contact not found' }, { status: 404 });
    }

    const updated = await softDeleteCustomerContact(
      id,
      contactId,
      organization.id,
      session.user.id
    );

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

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

    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

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