import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditDelete, auditUpdate } from '@/features/foundation/audit-log/service';
import {
  getQuotationDetail,
  listQuotationItems,
  softDeleteQuotationItem,
  updateQuotationItem
} from '@/features/crm/quotations/server/service';
import { quotationItemSchema } from '@/features/crm/quotations/schemas/quotation.schema';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

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

export async function PATCH(request: NextRequest, { params }: Params) {
  try {
    const { id, itemId } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmQuotationItemManage
    });
    const payload = quotationItemSchema.parse(await request.json());
    const quotation = await getQuotationDetail(id, organization.id);
    const before = (await listQuotationItems(id, organization.id)).find((item) => item.id === itemId);

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

    const updated = await updateQuotationItem(id, itemId, organization.id, session.user.id, payload);

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

    return NextResponse.json({
      success: true,
      message: 'Quotation item updated successfully',
      item: 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 quotation item' }, { status: 500 });
  }
}

export async function DELETE(_request: NextRequest, { params }: Params) {
  try {
    const { id, itemId } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmQuotationItemManage
    });
    const quotation = await getQuotationDetail(id, organization.id);
    const before = (await listQuotationItems(id, organization.id)).find((item) => item.id === itemId);

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

    const updated = await softDeleteQuotationItem(id, itemId, organization.id, session.user.id);

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

    return NextResponse.json({
      success: true,
      message: 'Quotation item 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 quotation item' }, { status: 500 });
  }
}
