<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\AnnouncementResource;
use App\Repositories\Contracts\AnnouncementRepositoryInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use OpenApi\Attributes as OA;

class AnnouncementController extends Controller
{
    public function __construct(private AnnouncementRepositoryInterface $repository) {}

    #[OA\Get(
        path: '/api/v1/announcements',
        summary: 'Duyuruları listele',
        tags: ['Announcements'],
        parameters: [
            new OA\Parameter(name: 'category', in: 'query', required: false, schema: new OA\Schema(type: 'string')),
            new OA\Parameter(name: 'featured', in: 'query', required: false, schema: new OA\Schema(type: 'boolean')),
            new OA\Parameter(name: 'search', in: 'query', required: false, schema: new OA\Schema(type: 'string')),
            new OA\Parameter(name: 'sort', in: 'query', required: false, schema: new OA\Schema(type: 'string')),
            new OA\Parameter(name: 'per_page', in: 'query', required: false, schema: new OA\Schema(type: 'integer', default: 15)),
        ],
        responses: [new OA\Response(response: 200, description: 'Duyuru listesi')],
    )]
    public function index(Request $request): AnonymousResourceCollection
    {
        $announcements = $this->repository->paginate(
            $request->only(['category', 'featured', 'search', 'sort']),
            $request->integer('per_page', 15),
        );

        return AnnouncementResource::collection($announcements);
    }

    #[OA\Get(
        path: '/api/v1/announcements/{slug}',
        summary: 'Duyuru detayı',
        tags: ['Announcements'],
        parameters: [new OA\Parameter(name: 'slug', in: 'path', required: true, schema: new OA\Schema(type: 'string'))],
        responses: [
            new OA\Response(response: 200, description: 'Duyuru detayı'),
            new OA\Response(response: 404, description: 'Duyuru bulunamadı'),
        ],
    )]
    public function show(string $slug): JsonResponse
    {
        $announcement = $this->repository->findBySlug($slug);

        if (! $announcement) {
            return response()->json(['message' => 'Duyuru bulunamadı.'], 404);
        }

        $announcement->load(['comments' => fn ($q) => $q->where('is_approved', true)->latest()]);

        return response()->json(new AnnouncementResource($announcement));
    }
}
