// packages/functions/src/vercel/api/crud/update.ts

/**
 * @fileoverview Update entity API handler
 * @description Vercel API route for updating entities
 *
 * @version 0.0.1
 * @since 0.0.1
 * @author AMBROISE PARK Consulting
 */

import type { UpdateEntityData } from '@donotdev/core/server';

import { handleError } from '../../../shared/errorHandling.js';
import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';

import {
  prepareForFirestore,
  transformFirestoreData,
} from '../../../shared/index.js';
import { updateMetadata } from '../../../shared/index.js';
import {
  validateDocument,
  assertAuthenticated,
} from '../../../shared/utils.js';

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

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

  try {
    // Verify authentication
    const uid = assertAuthenticated(req.headers.authorization);

    const { schema, id, payload } = req.body as UpdateEntityData<any>;

    if (!schema || !id || !payload) {
      throw handleError(new Error('Missing schema, id, or payload'));
    }

    // Validate the document against the schema
    validateDocument(payload as Record<string, any>, schema);

    // Prepare the document for Firestore and add metadata
    const documentData = {
      ...prepareForFirestore(payload),
      ...updateMetadata(uid),
    };

    // Update the document in Firestore
    const db = getFirebaseAdminFirestore();
    await db
      .collection(schema.metadata.collection)
      .doc(id)
      .update(documentData);

    // Retrieve the updated document
    const doc = await db.collection(schema.metadata.collection).doc(id).get();

    if (!doc.exists) {
      throw handleError(new Error('Document not found'));
    }

    // Transform the document data back to the application format
    const result = transformFirestoreData({
      id: doc.id,
      ...doc.data(),
    });

    return res.status(200).json(result);
  } catch (error) {
    throw handleError(error);
  }
}
