<?php

namespace App\Modules\HtlCampSchedule\Application\Availability;

use App\Modules\HtlCamp\Application\HtlCampIndexer;
use App\Modules\HtlCamp\Domain\IdHtlCamp;
use App\Modules\HtlCampSchedule\Domain\AvailabilityHtlCampSchedule;
use App\Modules\HtlCampSchedule\Domain\HtlCampSchedule;
use App\Modules\HtlCampSchedule\Domain\HtlCampScheduleAmountUsage;
use App\Modules\HtlCampSchedule\Domain\HtlCampScheduleAvailability;
use App\Modules\HtlCampSchedule\Domain\HtlCampScheduleDate;
use App\Modules\HtlCampSchedule\Domain\HtlCampScheduleDateSchedule;
use App\Modules\HtlCampSchedule\Domain\HtlCampScheduleFromCamp;
use App\Modules\HtlCampSchedule\Domain\HtlCampScheduleLock;
use App\Modules\HtlCampSchedule\Domain\HtlCampScheduleRepository;
use App\Modules\HtlCampSchedule\Domain\IdHtlCampSchedule;
use App\Modules\HtlCampSchedule\Domain\IndexHtlCampSchedule;

final class HtlCampScheduleAvailabilityFinder
{
    public function __construct(
        private HtlCampScheduleRepository $repository,
        private HtlCampIndexer $htlCampIndexer
    ) {
    }

    public function __invoke(IdHtlCamp $idHtlCamp, HtlCampScheduleDateSchedule $htlCampScheduleDate): HtlCampSchedule
    {
        $camp = $this->htlCampIndexer->__invoke($idHtlCamp);
        $index = $this->repository->find(new AvailabilityHtlCampSchedule($idHtlCamp, $htlCampScheduleDate, true));
        if (!$index) {
            $response = $this->insertBookingAtDate($idHtlCamp, $camp, $htlCampScheduleDate);
            return $this->repository->find(new IndexHtlCampSchedule(new IdHtlCampSchedule($response), true));
        }
        return $index;
    }

    private function insertBookingAtDate(IdHtlCamp $idHtlCamp, $camp, $htlCampScheduleDate)
    {
        $date = new HtlCampScheduleDateSchedule($htlCampScheduleDate->value());
        $date->setTime(0, 0, 0);
        return $this->repository->insert(new HtlCampSchedule(
            new IdHtlCampSchedule(0),
            HtlCampScheduleDate::now(),
            $date,
            new HtlCampScheduleFromCamp(HtlCampScheduleFromCamp::VALUE_TRUE),
            new HtlCampScheduleAvailability($camp['Response_Data'][0]->HtlCamp_Availability),
            new HtlCampScheduleAmountUsage(0),
            new HtlCampScheduleLock(1),
            $idHtlCamp
        ));
    }
}
