<?php

namespace App\Http\Controllers\Api\Settings;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Settings\PolicyShowRequest;
use App\Http\Resources\Settings\PolicyResource;
use App\Services\Policy\PolicyContentService;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class PolicyController extends BaseApiController
{
    public function __construct(private PolicyContentService $service)
    {
        parent::__construct();
    }

    public function school(PolicyShowRequest $request): JsonResponse
    {
        return $this->respondPolicy('school');
    }

    public function picture(PolicyShowRequest $request): JsonResponse
    {
        return $this->respondPolicy('picture');
    }

    private function respondPolicy(string $type): JsonResponse
    {
        try {
            $policy = $this->service->getPolicy($type);
        } catch (\InvalidArgumentException $e) {
            return $this->error('Policy not found.', Response::HTTP_NOT_FOUND);
        } catch (\Throwable $e) {
            return $this->error('Unable to load policy.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return $this->success([
            'policy' => new PolicyResource($policy),
        ]);
    }
}
