import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { updateCrmRoleProfile } from '@/features/foundation/role-management/server/service';
import {
  APPROVAL_AUTHORITIES,
  ALL_PERMISSIONS,
  OWNERSHIP_SCOPES,
  PERMISSIONS,
  SCOPE_MODES,
  type Permission
} from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

const updateRoleSchema = z.object({
  name: z.string().min(2),
  description: z.string().nullable().optional(),
  permissions: z
    .array(z.string())
    .refine(
      (values) => values.every((value) => ALL_PERMISSIONS.includes(value as Permission)),
      'Invalid permission key'
    )
    .transform((values) => values as Permission[]),
  branchScopeMode: z.enum(SCOPE_MODES),
  productScopeMode: z.enum(SCOPE_MODES),
  ownershipScope: z.enum(OWNERSHIP_SCOPES),
  approvalAuthority: z.enum(APPROVAL_AUTHORITIES),
  isActive: z.boolean()
});

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

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

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