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

/**
 * @fileoverview List entities API handler
 * @description Vercel API route for listing entities
 *
 * @version 0.0.1
 * @since 0.0.1
 * @author AMBROISE PARK Consulting
 */

import type { ListEntityData } 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,
      limit = 10,
      offset = 0,
    } = req.query as unknown as ListEntityData<any> & {
      limit?: string;
      offset?: string;
    };

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

    // Get documents from Firestore
    const db = getFirebaseAdminFirestore();
    let query: FirebaseFirestore.Query<FirebaseFirestore.DocumentData> =
      db.collection(schema.metadata.collection);

    // Apply limit and offset
    query = query.limit(parseInt(limit as string));
    query = query.offset(parseInt(offset as string));

    const snapshot = await query.get();

    // Transform the documents
    const documents = snapshot.docs.map((doc: any) => {
      const documentData = transformFirestoreData({
        id: doc.id,
        ...doc.data(),
      });
      return filterVisibleFields(documentData, schema, false);
    });

    return res.status(200).json({
      documents,
      total: snapshot.size,
      limit: parseInt(limit as string),
      offset: parseInt(offset as string),
    });
  } catch (error) {
    const errorResponse = handleError(error);
    return res.status(500).json(errorResponse);
  }
}
