import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditDelete, auditUpdate } from '@/features/foundation/audit-log/service';
import {
  getQuotationActivity,
  getQuotationDetail,
  softDeleteQuotation,
  updateQuotation
} from '@/features/crm/quotations/server/service';
import { quotationSchema } 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 }>;
};

export async function GET(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmQuotationRead
    });
    const [quotation, activity] = await Promise.all([
      getQuotationDetail(id, organization.id),
      getQuotationActivity(id, organization.id)
    ]);

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Quotation loaded successfully',
      quotation,
      activity
    });
  } 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 load quotation' }, { status: 500 });
  }
}

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

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

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

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

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

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