<?php

namespace App\Domains\Ticket\Controllers;

use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Exceptions\TicketNotAvailableException;
use App\Domains\Ticket\Models\Ticket;
use App\Domains\Ticket\Requests\DownloadTicketsPdfRequest;
use App\Domains\Ticket\Resources\TicketResource;
use App\Domains\Ticket\Services\TicketPdfService;
use App\Domains\Ticket\Services\TicketPresentationResolver;
use App\Domains\Ticket\Services\TicketValidityResolver;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class TicketController extends Controller
{
    public function __construct(private readonly TicketPdfService $ticketPdfService) {}

    public function index(Request $request, Tenant $tenant): JsonResponse
    {
        $tickets = Ticket::query()
            ->where('tenant_code', $tenant->codigo)
            ->where('user_id', $request->user()->getKey())
            ->with([...TicketValidityResolver::RELATIONS, ...TicketPresentationResolver::RELATIONS])
            ->orderByDesc('id')
            ->get();

        return TicketResource::collection($tickets)->response();
    }

    public function downloadPdf(DownloadTicketsPdfRequest $request, Tenant $tenant): Response
    {
        $ticketIds = $request->validated('ticket_ids');
        $tickets = Ticket::query()
            ->where('tenant_code', $tenant->codigo)
            ->where('user_id', $request->user()->getKey())
            ->whereIn('id', $ticketIds)
            ->with([...TicketValidityResolver::RELATIONS, ...TicketPresentationResolver::RELATIONS])
            ->orderByDesc('id')
            ->get();

        if ($tickets->count() !== count($ticketIds)) {
            throw new TicketNotAvailableException(__('api.ticket.not_available'));
        }

        return $this->ticketPdfService->download($tenant, $tickets);
    }
}
