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

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

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

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

import {
  prepareForFirestore,
  transformFirestoreData,
} from '../../../shared/index.js';
import { createMetadata } 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 !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

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

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

    if (!schema || !payload) {
      throw handleError(new Error('Missing schema 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),
      ...createMetadata(uid),
    };

    // Save the document to Firestore
    const db = getFirebaseAdminFirestore();
    const docRef = await db
      .collection(schema.metadata.collection)
      .add(documentData);

    // Retrieve the created document
    const doc = await docRef.get();

    // 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);
  }
}
