import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { cloneCrmRoleProfile } from '@/features/foundation/role-management/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

const cloneRoleSchema = z.object({
  code: z.string().min(2),
  name: z.string().min(2),
  description: z.string().nullable().optional()
});

type RouteProps = {
  params: Promise<{ code: string }>;
};

export async function POST(request: NextRequest, props: RouteProps) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmRoleCreate
    });
    const payload = cloneRoleSchema.parse(await request.json());
    const { code } = await props.params;
    const role = await cloneCrmRoleProfile(organization.id, session.user.id, code, payload);

    return NextResponse.json(
      {
        success: true,
        message: 'CRM role cloned successfully',
        role
      },
      { 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 });
    }

    return NextResponse.json({ message: 'Unable to clone CRM role' }, { status: 500 });
  }
}
