import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { submitQuotationForApproval } from '@/features/crm/approval/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 submitSchema = z.object({
  remark: z.string().optional()
});

export async function POST(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalSubmit
    });
    const payload = submitSchema.parse(await request.json());

    await submitQuotationForApproval({
      organizationId: organization.id,
      userId: session.user.id,
      quotationId: id,
      remark: payload.remark,
      accessContext: buildCrmSecurityContext({
        organizationId: organization.id,
        userId: session.user.id,
        membership
      })
    });

    return NextResponse.json({
      success: true,
      message: 'Quotation submitted approval 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 }
      );
    }
    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }
    return NextResponse.json({ message: 'Unable submit quotation for approval' }, { status: 500 });
  }
}
