import { NextRequest, NextResponse } from 'next/server';
import { cancelApproval, getApprovalRequest } from '@/features/foundation/approval/server/service';
import {
  auditCrmSecurityEvent,
  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 }>;
};

export async function GET(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalRead
    });
    const accessContext = buildCrmSecurityContext({
      organizationId: organization.id,
      userId: session.user.id,
      membership
    });
    const approval = await getApprovalRequest(id, organization.id, accessContext);

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Approval detail loaded successfully',
      approval
    });
  } catch (error) {
    if (error instanceof AuthError) {
      if (error.status === 403) {
        const session = await requireOrganizationAccess({
          permission: PERMISSIONS.crmApprovalRead
        }).catch(() => null);

        if (session) {
          await auditCrmSecurityEvent({
            organizationId: session.organization.id,
            userId: session.session.user.id,
            action: 'approval_scope_violation',
            entityType: 'crm_approval_request',
            entityId: (await params).id,
            reason: 'Approval detail visibility denied'
          });
        }
      }
      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 approval detail' }, { status: 500 });
  }
}

export async function DELETE(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalSubmit
    });
    await cancelApproval(id, organization.id, session.user.id);

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