<?php

namespace App\Http\Controllers\API\SuperAdmin;

use App\Http\Controllers\API\BaseApiController;
use App\Models\Resource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SuperAdminResourceController extends BaseApiController
{
    public function index(): JsonResponse
    {
        return $this->successResponse(Resource::withTrashed()->orderBy('sort_order')->get());
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'title'        => 'required|string|max:255',
            'description'  => 'nullable|string',
            'type'         => 'required|in:guia,legislacao,faq,contacto,outro',
            'category'     => 'required|in:primeiros_passos,legal_regulatorio,tributacao,financiamento,sectorial,outro',
            'file_url'     => 'nullable|string',
            'external_url' => 'nullable|url',
            'reference'    => 'nullable|string|max:100',
            'pages'        => 'nullable|integer|min:1',
            'is_active'    => 'boolean',
            'sort_order'   => 'integer|min:0',
        ]);

        $resource = Resource::create($data);
        return $this->successResponse($resource, 'Recurso criado', 201);
    }

    public function show(int $id): JsonResponse
    {
        return $this->successResponse(Resource::findOrFail($id));
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $resource = Resource::findOrFail($id);
        $resource->update($request->only([
            'title', 'description', 'type', 'category', 'file_url',
            'external_url', 'reference', 'pages', 'is_active', 'sort_order',
        ]));
        return $this->successResponse($resource, 'Recurso actualizado');
    }

    public function destroy(int $id): JsonResponse
    {
        Resource::findOrFail($id)->delete();
        return $this->successResponse(null, 'Recurso removido');
    }
}
