<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Concerns\DestroysCatalogItem;
use App\Http\Requests\StoreAreaAdminRequest;
use App\Http\Requests\UpdateAreaAdminRequest;
use App\Models\Area;
use App\Support\CatalogCodeGenerator;
use App\Models\AreaSetting;
use App\Services\AreaPermissionSyncService;
use App\Support\CatalogDeletionGuard;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class AreaAdminController extends Controller
{
    use DestroysCatalogItem;

    public function __construct(
        private readonly AreaPermissionSyncService $areaPermissionSync,
    ) {}

    public function index(): JsonResponse
    {
        $this->authorize('create', Area::class);

        $rows = Area::query()
            ->with('settings')
            ->orderBy('sort_order')
            ->get()
            ->map(fn (Area $a) => $this->toResource($a));

        return response()->json([
            'data' => $rows,
            'meta' => null,
            'errors' => null,
        ], JsonResponse::HTTP_OK);
    }

    public function store(StoreAreaAdminRequest $request): JsonResponse
    {
        $data = $request->validated();
        $code = CatalogCodeGenerator::fromName($data['name'], Area::class, 'code', 'area');

        $area = DB::transaction(function () use ($data, $code) {
            $area = Area::create([
                'code' => $code,
                'name' => $data['name'],
                'sort_order' => $data['sort_order'] ?? 0,
                'is_active' => $data['is_active'] ?? true,
                'requires_scan_twice' => $data['requires_scan_twice'] ?? false,
                'floor_label' => $data['floor_label'] ?? null,
            ]);
            AreaSetting::create([
                'area_id' => $area->id,
                'is_enabled' => $data['is_enabled'] ?? true,
            ]);

            return $area->load('settings');
        });

        $this->areaPermissionSync->ensurePermissionsForArea($area);

        return response()->json([
            'data' => $this->toResource($area),
            'meta' => null,
            'errors' => null,
        ], JsonResponse::HTTP_CREATED);
    }

    public function update(UpdateAreaAdminRequest $request, Area $area): JsonResponse
    {
        $data = $request->validated();

        DB::transaction(function () use ($area, $data): void {
            if (array_key_exists('is_enabled', $data)) {
                $area->settings()->updateOrCreate(
                    ['area_id' => $area->id],
                    ['is_enabled' => (bool) $data['is_enabled']]
                );
                unset($data['is_enabled']);
            }
            $area->fill($data);
            $area->save();
        });

        $area->refresh()->load('settings');

        return response()->json([
            'data' => $this->toResource($area),
            'meta' => null,
            'errors' => null,
        ], JsonResponse::HTTP_OK);
    }

    /**
     * Desactiva el área para operación (is_enabled=false). No borra presencias ni escaneos.
     */
    public function disable(Area $area): JsonResponse
    {
        $this->authorize('update', $area);

        $area->settings()->updateOrCreate(
            ['area_id' => $area->id],
            ['is_enabled' => false]
        );

        $area->refresh()->load('settings');

        return response()->json([
            'data' => $this->toResource($area),
            'message' => 'Área desactivada para operación (historial intacto).',
            'meta' => null,
            'errors' => null,
        ], JsonResponse::HTTP_OK);
    }

    public function destroy(Area $area): JsonResponse
    {
        $this->authorize('delete', $area);

        return $this->destroyCatalogItem(
            CatalogDeletionGuard::area($area),
            fn () => $area->delete(),
        );
    }

    /**
     * @return array<string, mixed>
     */
    private function toResource(Area $a): array
    {
        return [
            'id' => $a->id,
            'code' => $a->code,
            'name' => $a->name,
            'sort_order' => $a->sort_order,
            'is_active' => (bool) $a->is_active,
            'requires_scan_twice' => (bool) $a->requires_scan_twice,
            'floor_label' => $a->floor_label,
            'is_enabled' => (bool) ($a->settings?->is_enabled ?? false),
        ];
    }
}
