<?php

namespace App\Master\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\App;
use Mtc\MercuryDataModels\Contracts\FeatureFlag;
use Mtc\MercuryDataModels\TenantFeature;

class FeatureFlagController extends Controller
{
    public function index(): array
    {
        $flags = collect(config('features.all', []))
            ->filter(fn (string $class) => class_exists($class))
            ->map(fn (string $class, string $key) => App::make($class))
            ->filter(fn ($instance) => $instance instanceof FeatureFlag);

        $counts = TenantFeature::query()
            ->selectRaw('feature, COUNT(*) as tenant_count')
            ->groupBy('feature')
            ->pluck('tenant_count', 'feature');

        return $flags->map(fn (FeatureFlag $flag, string $key) => [
            'key' => $key,
            'name' => $flag->name(),
            'description' => $flag->description(),
            'tenant_count' => $counts->get($key, 0),
        ])->values()->all();
    }

    public function show(string $feature): array
    {
        $allFlags = config('features.all', []);

        if (! isset($allFlags[$feature]) || ! class_exists($allFlags[$feature])) {
            abort(404, 'Feature flag not found');
        }

        $flag = App::make($allFlags[$feature]);

        if (! $flag instanceof FeatureFlag) {
            abort(404, 'Feature flag not found');
        }

        $tenants = TenantFeature::query()
            ->where('feature', $feature)
            ->with('tenant:id,name')
            ->get()
            ->map(fn (TenantFeature $tf) => [
                'id' => $tf->tenant->id,
                'name' => $tf->tenant->name,
            ]);

        return [
            'key' => $feature,
            'name' => $flag->name(),
            'description' => $flag->description(),
            'tenants' => $tenants,
        ];
    }
}
