import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import {
  createApprovalEscalationPolicy,
  listApprovalEscalationPolicies
} from '@/features/foundation/approval-automation/server/service';
import { approvalEscalationPolicySchema } from '@/features/foundation/approval-automation/schemas';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

export async function GET() {
  try {
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalEscalationManage
    });
    const items = await listApprovalEscalationPolicies(organization.id);

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Approval escalation policies 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 approval escalation policies' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalEscalationManage
    });
    const payload = approvalEscalationPolicySchema.parse(await request.json());
    const created = await createApprovalEscalationPolicy(
      organization.id,
      session.user.id,
      payload
    );

    return NextResponse.json(
      {
        success: true,
        message: 'Approval escalation policy created successfully',
        item: 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 approval escalation policy' },
      { status: 500 }
    );
  }
}
