<?php

namespace App\Http\Controllers\Admin\Registry;

use App\Http\Controllers\Admin\CoLendingController;
use App\Http\Controllers\Admin\DaSystemDataController;
use App\Http\Controllers\Admin\Odoo\OdooController;
use App\Http\Controllers\Admin\UCIC\UCICController;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class RegistryService extends Controller
{
    /**
     * Single source of truth for all registry services.
     *
     * To add a new service, add ONE entry here:
     *   'service-key' => [
     *       'label'      => 'Human Readable Label',
     *       'controller' => MyController::class,   // must implement static registry(): array
     *   ]
     */
    protected static $registry = [
        'direct-assignment' => [
            'label'      => 'Direct Assignment',
            'controller' => DaSystemDataController::class,
        ],
        'co-lending' => [
            'label'      => 'Co-Lending',
            'controller' => CoLendingController::class,
        ],
        'ucic' => [
            'label'      => 'UCIC',
            'controller' => UCICController::class,
        ],
        'odoo' => [
            'label'      => 'Odoo',
            'controller' => OdooController::class,
        ],
    ];

    private $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * Render the registry index page.
     */
    public function registry()
    {
        return view('admin.registry.index');
    }

    /**
     * Return registry data as JSON.
     *
     * GET /admin/registry/all          -> all services
     * GET /admin/registry/{service}    -> specific service
     */
    public function getRegistry($service)
    {
        $map = static::$registry;

        if ($service !== 'all') {
            if (!isset($map[$service])) {
                return response()->json(['data' => [], 'message' => 'Service not found.'], 404);
            }
            $map = [$service => $map[$service]];
        }

        $result = [];
        foreach ($map as $key => $config) {
            $result[$key] = [
                'label' => $config['label'],
                'items' => call_user_func([$config['controller'], 'registry']),
            ];
        }

        return response()->json(['data' => $result, 'message' => 'Data retrieved successfully.'], 200);
    }
}
