import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditCreate } from '@/features/foundation/audit-log/service';
import {
  createQuotationRevision,
  getQuotationDetail,
  listQuotationRevisions
} from '@/features/crm/quotations/server/service';
import { quotationRevisionSchema } 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 items = await listQuotationRevisions(id, organization.id);

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

export async function POST(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmQuotationRevisionCreate
    });
    const payload = quotationRevisionSchema.parse(await request.json());
    const quotation = await getQuotationDetail(id, organization.id);
    const created = await createQuotationRevision(
      id,
      organization.id,
      session.user.id,
      payload.revisionRemark
    );

    await auditCreate({
      organizationId: organization.id,
      branchId: quotation.branchId,
      userId: session.user.id,
      entityType: 'crm_quotation',
      entityId: created.id,
      afterData: created
    });

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