<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Ad;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;

class AdController extends Controller
{
    #[OA\Get(
        path: '/api/ads/list',
        operationId: 'adsList',
        summary: 'List all approved advertisements',
        description: 'Returns a paginated list of currently active and approved vendor advertisements. Can be filtered by type.',
        security: [['passport' => []]],
        tags: ['Ads'],
        parameters: [
            new OA\Parameter(name: 'type', in: 'query', required: false,
                description: 'Filter by ad type',
                schema: new OA\Schema(type: 'string', enum: ['banner', 'video'])),
            new OA\Parameter(name: 'page', in: 'query', required: false,
                schema: new OA\Schema(type: 'integer', default: 1)),
        ],
        responses: [
            new OA\Response(response: 200, description: 'Paginated ads list',
                content: new OA\JsonContent(properties: [
                    new OA\Property(property: 'data', type: 'object',
                        properties: [
                            new OA\Property(property: 'data', type: 'array',
                                items: new OA\Items(ref: '#/components/schemas/AdResource')),
                            new OA\Property(property: 'meta', ref: '#/components/schemas/PaginationMeta'),
                        ]),
                ])),
            new OA\Response(response: 401, description: 'Unauthenticated',
                content: new OA\JsonContent(ref: '#/components/schemas/UnauthorizedError')),
        ]
    )]
    public function list(Request $request)
    {
        $query = Ad::approved()->with('vendor');

        if ($request->type) {
            $query->where('type', $request->type);
        }

        // Track impressions
        $query->increment('impressions');

        $ads = $query->latest()->paginate(20);
        return response()->json(['data' => $ads]);
    }
}
