<?php

namespace App\Http\Controllers\Passenger\GroupPassengerMedia;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Helpers\ResponseBuilder;
use App\Http\History\HistoryData;
use App\Http\History\HistoryTables;
use App\Modules\GroupPassengerMedia\Application\Create\CreateGroupPassengerMediaQuery;
use App\Modules\GroupPassengerMedia\Application\Create\CreateGroupPassengerMediaResponse;
use App\Modules\GroupPassengerMedia\Domain\GroupPassengerMediaHasThumbnail;
use App\Modules\GroupPassengerMedia\Domain\GroupPassengerMediaStatus;
use App\Modules\GroupPassengerMedia\Domain\GroupPassengerMediaType;
use App\Modules\Shared\Validator\Infraestructure\LaravelValidator;
use App\Modules\GroupPassengerMedia\Infrastructure\GroupPassengerMediaValidators;
use App\Modules\Media\Application\Create\CreateMediaQuery;
use App\Modules\Media\Application\Create\CreateMediaResponse;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use App\Modules\Shared\Domain\Transaction;
use App\Modules\Shared\Exceptions\BasicRequestException;
use Illuminate\Support\Facades\DB;

class GroupPassengerMediaInsertController extends Controller
{
    private $domain;
    private HistoryData $history;

    public function __construct(
        private QueryBus $queryBus,
        private Transaction $transaction
    ) {
        $this->domain = "GroupPassengerMedia";
        $this->history = new HistoryData(HistoryTables::GROUP_PASSENGER_MEDIA);
    }

    private function formatName(string $name)
    {
        return preg_replace('/[^A-Za-z0-9áéíóúÁÉÍÓÚñÑüÜ() -]/u', '', $name);
    }

    public function __invoke(Request $request)
    {
        (new LaravelValidator())->validate(
            $request->all(),
            $this->domain,
            GroupPassengerMediaValidators::getInsert()
        );

        $groupPassenger = DB::select('call sp_group_passenger_index(?,?)', [$request->input('Id_GroupPassenger'), '']);
        if (!count($groupPassenger)) {
            return new BasicRequestException(404, 404, 'Pasajero de grupo no encontrado');
        }
        $group = DB::select('call sp_group_index(?)', [$groupPassenger[0]->Id_Group]);
        if (!count($group)) {
            return new BasicRequestException(404, 404, 'Group no encontrado');
        }

        $groupName = $this->formatName($group[0]->Group_DateStart
            . ' ' . $groupPassenger[0]->Booking_Code
            . ' ' . $groupPassenger[0]->Passenger_Name . ' ' . $groupPassenger[0]->Passenger_LastName
            . ' (' . $group[0]->Service_Code . ')');

        /** @var CreateMediaResponse $mediaResponse */
        $mediaResponse = $this->queryBus->ask(new CreateMediaQuery(
            'File',
            'group_passenger' . DIRECTORY_SEPARATOR . 'media',
            true,
            $groupName
        ));

        $mediaType = GroupPassengerMediaType::fromMediaType($mediaResponse->mediaType);

        $this->transaction->begin();
        /** @var CreateGroupPassengerMediaResponse $response */
        $response = $this->queryBus->ask(new CreateGroupPassengerMediaQuery(
            $mediaResponse->url,
            $mediaResponse->thumbnail,
            $mediaResponse->largeThumbnail,
            '',
            $mediaResponse->extension,
            $mediaResponse->filesize,
            $mediaType->value(),
            $mediaResponse->thumbnail ? GroupPassengerMediaHasThumbnail::VALUE_TRUE : GroupPassengerMediaHasThumbnail::VALUE_FALSE,
            '',
            GroupPassengerMediaStatus::ACTIVE,
            $request->input('Id_GroupPassenger'),
        ));

        $this->transaction->commit();
        $this->history->insertBasic($request, $response->id());
        return ResponseBuilder::Response([
            "Response_Status"           => 200,
            "Response_Code"             => 200,
            "Response_Data"             => ['id' => $response->id()],
            "Response_Domain"           => $this->domain,
            "Response_Message"          => 'Media uploaded successfully',
            "Response_Error_Message"    => '',
            "Response_Error_Reason"     => '',
        ]);
    }
}
