<?php

namespace App\Http\Requests;

use App\Facades\Feature;
use App\Repositories\DealBuilderRepository;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;
use Illuminate\Validation\ValidationException;
use Mtc\MercuryDataModels\DealBuilder\Deal;

class DealBuilderRequest extends FormRequest
{
    private DealBuilderRepository $repository;

    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return Feature::isEnabled('build-a-deal');
    }

    public function deal(): Deal
    {
        $dealId = Session::get(DealBuilderRepository::DEAL_SESSION_KEY);

        if (!$dealId) {
            throw ValidationException::withMessages(['deal' => __('deal_builder.no_active_deal')]);
        }

        $deal = $this->dealBuilder()->get($dealId);

        if ($deal->status_id > 0) {
            Session::forget(DealBuilderRepository::DEAL_SESSION_KEY);
            throw ValidationException::withMessages(['deal' => __('deal_builder.deal_already_submitted')]);
        }

        return $deal;
    }

    public function dealBuilder(): DealBuilderRepository
    {
        if (!isset($this->repository)) {
            $this->repository = App::make(DealBuilderRepository::class);
        }
        return $this->repository;
    }
}
