<?php

namespace App\Http\Controllers\Owner\GroupProviderMedia;

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\GroupProvider\Application\Index\IndexGroupProviderQuery;
use App\Modules\GroupProviderMedia\Application\Create\CreateGroupProviderMediaQuery;
use App\Modules\GroupProviderMedia\Application\Create\CreateGroupProviderMediaResponse;
use App\Modules\GroupProviderMedia\Domain\GroupProviderMediaHasThumbnail;
use App\Modules\GroupProviderMedia\Domain\GroupProviderMediaStatus;
use App\Modules\GroupProviderMedia\Domain\GroupProviderMediaType;
use App\Modules\Shared\Validator\Infraestructure\LaravelValidator;
use App\Modules\GroupProviderMedia\Infrastructure\GroupProviderMediaValidators;
use App\Modules\Media\Application\Create\CreateMediaQuery;
use App\Modules\Media\Application\Create\CreateMediaResponse;
use App\Modules\Room\Domain\RoomNotFound;
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 GroupProviderMediaInsertController extends Controller
{
    private $domain;
    private HistoryData $history;

    public function __construct(
        private QueryBus $queryBus,
        private Transaction $transaction
    ) {
        $this->domain = "GroupProviderMedia";
        $this->history = new HistoryData(HistoryTables::GROUP_PROVIDER_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,
            GroupProviderMediaValidators::getInsert()
        );

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

        $groupName = $this->formatName($group[0]->Group_DateStart
            . ' ' . $groupProvider[0]->Provider_NickName
            . ' (' . $group[0]->Service_Code . ')');

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

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

        $this->transaction->begin();
        /** @var CreateGroupProviderMediaResponse $response */
        $response = $this->queryBus->ask(new CreateGroupProviderMediaQuery(
            $mediaResponse->url,
            $mediaResponse->thumbnail,
            $mediaResponse->largeThumbnail,
            '',
            $mediaResponse->extension,
            $mediaResponse->filesize,
            $mediaType->value(),
            $mediaResponse->thumbnail ? GroupProviderMediaHasThumbnail::VALUE_TRUE : GroupProviderMediaHasThumbnail::VALUE_FALSE,
            '',
            GroupProviderMediaStatus::ACTIVE,
            $request->input('Id_GroupProvider'),
        ));
        $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"     => '',
        ]);
    }
}
