<?php

namespace App\Modules\Dashboard\Services;

use App\Modules\Admin\Tenancy\Models\Module as ModuleModel;
use App\Modules\Dashboard\DTOs\ModuleCardData;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Route;

class DashboardModuleCardBuilder
{
    /**
     * @param  list<string>  $enabledSlugs
     * @param  Collection<int, ModuleModel>  $activeModules
     * @return list<ModuleCardData>
     */
    public function build(array $enabledSlugs, Collection $activeModules): array
    {
        $enabledSet = array_flip($enabledSlugs);
        $routes = config('dashboard.entry_routes', []);
        $rows = [];

        foreach ($activeModules as $model) {
            $slug = (string) $model->slug;
            $enabled = isset($enabledSet[$slug]);
            $routeName = $routes[$slug] ?? null;
            $href = $enabled && $routeName && Route::has($routeName)
                ? route($routeName)
                : null;

            $rows[] = new ModuleCardData(
                slug: $slug,
                name: $this->moduleName($model, $slug),
                description: $this->moduleDescription($model, $slug),
                icon: $this->moduleIcon($model, $slug),
                enabled: $enabled,
                href: $href,
            );
        }

        return $rows;
    }

    private function moduleIcon(ModuleModel $model, string $slug): string
    {
        if ($model->icon !== null && $model->icon !== '') {
            return (string) $model->icon;
        }
        $key = 'modules.catalog.'.$slug.'.icon';

        return Lang::has($key) ? (string) __($key) : 'fe fe-grid';
    }

    private function moduleName(ModuleModel $model, string $slug): string
    {
        $key = 'modules.catalog.'.$slug.'.name';
        if (Lang::has($key)) {
            return (string) __($key);
        }

        return (string) $model->name;
    }

    private function moduleDescription(ModuleModel $model, string $slug): string
    {
        $key = 'modules.catalog.'.$slug.'.description';
        if (Lang::has($key)) {
            return (string) __($key);
        }
        $desc = $model->description;

        return $desc !== null && $desc !== '' ? (string) $desc : (string) __('modules.catalog.fallback_description');
    }
}
