// packages/functions/src/vercel/api/auth/set-custom-claims.ts

/**
 * @fileoverview Set custom claims API handler
 * @description Vercel API route for setting custom user claims
 *
 * @version 0.0.1
 * @since 0.0.1
 * @author AMBROISE PARK Consulting
 */

import { getFirebaseAdminAuth } from '@donotdev/firebase/server';

import { handleError } from '../../../shared/errorHandling.js';
import { assertAuthenticated } from '../../../shared/utils.js';

import type { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const uid = assertAuthenticated(req.headers.authorization);
    const { customClaims } = req.body;

    if (!customClaims || typeof customClaims !== 'object') {
      throw handleError(new Error('customClaims must be an object'));
    }

    const user = await getFirebaseAdminAuth().getUser(uid);
    const currentClaims = user.customClaims || {};

    // Merge with existing claims
    const updatedClaims = { ...currentClaims, ...customClaims };

    await getFirebaseAdminAuth().setCustomUserClaims(uid, updatedClaims);

    return res.status(200).json({ success: true, customClaims: updatedClaims });
  } catch (error) {
    throw handleError(error);
  }
}
