import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditAction } from '@/features/foundation/audit-log/service';
import {
  assignCustomerOwner,
  clearCustomerOwner,
  getCustomerDetail
} from '@/features/crm/customers/server/service';
import { buildCrmSecurityContext } from '@/features/crm/security/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

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

const ownerSchema = z.object({
  ownerUserId: z.string().min(1, 'Owner user is required'),
  remark: z.string().optional().nullable()
});

const clearOwnerSchema = z.object({
  remark: z.string().optional().nullable()
});

export async function PATCH(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmCustomerOwnerManage
    });
    const payload = ownerSchema.parse(await request.json());
    const accessContext = buildCrmSecurityContext({
      organizationId: organization.id,
      userId: session.user.id,
      membership
    });
    const before = await getCustomerDetail(id, organization.id, accessContext);
    const updated = await assignCustomerOwner(
      id,
      organization.id,
      session.user.id,
      payload,
      accessContext
    );

    await auditAction({
      organizationId: organization.id,
      branchId: updated.branchId,
      userId: session.user.id,
      entityType: 'crm_customer_owner',
      entityId: id,
      action: before.ownerUserId ? 'change_owner' : 'assign_owner',
      beforeData: {
        customerId: id,
        oldOwnerUserId: before.ownerUserId
      },
      afterData: {
        customerId: id,
        newOwnerUserId: payload.ownerUserId,
        remark: payload.remark ?? null
      }
    });

    return NextResponse.json({
      success: true,
      message: 'Customer owner updated successfully'
    });
  } 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]/owner failed', error);
    return NextResponse.json({ message: 'Unable to update customer owner' }, { status: 500 });
  }
}

export async function DELETE(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmCustomerOwnerManage
    });
    const payload = clearOwnerSchema.parse(
      request.method === 'DELETE' ? (await request.json().catch(() => ({}))) : {}
    );
    const accessContext = buildCrmSecurityContext({
      organizationId: organization.id,
      userId: session.user.id,
      membership
    });
    const before = await getCustomerDetail(id, organization.id, accessContext);
    const updated = await clearCustomerOwner(
      id,
      organization.id,
      session.user.id,
      payload,
      accessContext
    );

    await auditAction({
      organizationId: organization.id,
      branchId: updated.branchId,
      userId: session.user.id,
      entityType: 'crm_customer_owner',
      entityId: id,
      action: 'clear_owner',
      beforeData: {
        customerId: id,
        oldOwnerUserId: before.ownerUserId
      },
      afterData: {
        customerId: id,
        newOwnerUserId: null,
        remark: payload.remark ?? null
      }
    });

    return NextResponse.json({
      success: true,
      message: 'Customer owner cleared successfully'
    });
  } 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('DELETE /api/crm/customers/[id]/owner failed', error);
    return NextResponse.json({ message: 'Unable to clear customer owner' }, { status: 500 });
  }
}
