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

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

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

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

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

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

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

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

    const { schema, id } = req.query as unknown as GetEntityData<any>;

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

    // Get the document from Firestore
    const db = getFirebaseAdminFirestore();
    const doc = await db
      .collection(schema.metadata.collection)
      .doc(id as string)
      .get();

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

    // Transform the document data
    const documentData = transformFirestoreData({
      id: doc.id,
      ...doc.data(),
    });

    // Filter visible fields based on schema
    const filteredData = filterVisibleFields(documentData, schema, false);

    return res.status(200).json(filteredData);
  } catch (error) {
    const errorResponse = handleError(error);
    return res.status(500).json(errorResponse);
  }
}
