import type { HttpContext } from '@adonisjs/core/http';
import Collection from '#models/collection';

export default class CollectionsController {
    public async show({ params, response }: HttpContext) {
        // Get the collection id from route parameters
        const collectionId = params.id;

        // Find the selected collection by id
        const collection = await Collection.find(collectionId);
        if (!collection) {
            return response.status(404).json({ message: 'Collection not found' });
        }

        // Query for narrower concepts: collections whose parent_id equals the selected collection's id
        const narrowerCollections = await Collection.query().where('parent_id', collection.id) || [];

        // For broader concept, if the selected collection has a parent_id fetch that record (otherwise null)
        const broaderCollection: Collection[] | never[] | null = await (async () => {
            if (collection.parent_id) {
              // Try to fetch the parent...
              const parent = await Collection.find(collection.parent_id)
              // If found, return it wrapped in an array; if not found, return null (or empty array if you prefer)
              return parent ? [parent] : null
            }
            return []
          })()

        // Return the selected collection along with its narrower and broader concepts in JSON format
        return response.json({
            selectedCollection: collection,
            narrowerCollections,
            broaderCollection,
        });
    }
}
