<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1\Admin;

use App\Http\Controllers\Controller;
use App\Models\Theme;
use App\Services\Theme\ThemeManager;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

class ThemeController extends Controller
{
    public function __construct(protected ThemeManager $themes) {}

    protected function ensureAdmin(Request $request): void
    {
        $user = $request->user();
        if (! $user || ! ($user->hasRole('super_admin') || $user->hasRole('tenant_admin'))) {
            throw new AccessDeniedHttpException('ADMIN_ONLY');
        }
    }

    public function index(Request $request): JsonResponse
    {
        $this->ensureAdmin($request);
        $items = Theme::query()->orderByDesc('is_active')->orderBy('name')->get();
        return response()->json([
            'data' => $items->map(fn($t) => [
                'id' => $t->id,
                'slug' => $t->slug,
                'name' => $t->name,
                'version' => $t->version,
                'author' => $t->author,
                'description' => $t->description,
                'type' => $t->type,
                'is_active' => (bool) $t->is_active,
                'screenshot_url' => $t->screenshot_url,
                'path' => $t->path,
                'settings' => $t->settings,
            ]),
        ]);
    }

    public function scan(Request $request): JsonResponse
    {
        $this->ensureAdmin($request);
        $found = $this->themes->scan();
        return response()->json(['scanned' => $found->count()]);
    }

    public function activate(Request $request, string $slug): JsonResponse
    {
        $this->ensureAdmin($request);
        $ok = $this->themes->activate($slug);
        return response()->json(['ok' => $ok], $ok ? 200 : 404);
    }

    public function preview(Request $request, string $slug): JsonResponse
    {
        $this->ensureAdmin($request);
        $theme = Theme::query()->where('slug', $slug)->first();
        if (! $theme) return response()->json(['error' => 'NOT_FOUND'], 404);
        return response()->json([
            'preview_url' => "/?theme=$slug",
            'css_url' => config('theme.themes_url', '/themes') . "/$slug/assets/theme.css",
        ]);
    }

    public function upload(Request $request): JsonResponse
    {
        $this->ensureAdmin($request);
        $request->validate(['file' => 'required|file|max:51200']);
        $tmp = $request->file('file')->getRealPath();
        try {
            $theme = $this->themes->installFromZip($tmp);
        } catch (\Throwable $e) {
            return response()->json(['error' => $e->getMessage()], 422);
        }
        return response()->json(['slug' => $theme?->slug, 'name' => $theme?->name], 201);
    }

    public function destroy(Request $request, string $slug): JsonResponse
    {
        $this->ensureAdmin($request);
        $ok = $this->themes->uninstall($slug);
        return response()->json(['ok' => $ok], $ok ? 200 : 422);
    }
}
