<?php

namespace App\Http\Controllers\Base;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Base\ContentRequest;
use App\Http\Resources\Inquiry\ContentResource;
use App\Models\Content;
use App\Models\Language;
use Exception;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Throwable;

/**
 * @OA\Get(
 *   path="/api/base/content",
 *   tags={"Base"},
 *   summary="Get Site Contents",
 *   operationId="base_content",
 *   security={{"auth":{}}},
 *
 *   @OA\Parameter(name="Accept-Language", in="header", description="Accept-Language", required=true, example="en", @OA\Schema(type="string")),
 *   @OA\Parameter(name="API-Key", in="header", description="API-Key", required=true, example="", @OA\Schema(type="string")),
 *
 *   @OA\Response(response=200, description="success")
 * )
 */
class ContentController extends ApiController
{
    public function __invoke(ContentRequest $request): JsonResponse
    {
        try {
            $data = $this->sanitize($request, [
                'language' => $request->validated('language'),
            ]);
            $languageId = Language::query()->where('code', $data['language'])->value('id');
            throw_if(
                !$content = Content::query()->where(['language_id' => $languageId, 'is_active' => 1])->first(),
                new Exception('Content not found', Response::HTTP_BAD_REQUEST),
            );
            return $this->success($this->transform($content, ContentResource::class));
        } catch (Throwable $e) {
            return $this->error($e->getMessage(), status: $e->getCode());
        }
    }
}
