<?php

namespace App\Http\Requests\Admin;

use App\Models\MatchContest;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

class UpdateContestRequest extends FormRequest
{
    public function authorize(): bool
    {
        return auth()->check();
    }

    protected function prepareForValidation(): void
    {
        $contestType = $this->input('contest_type', MatchContest::TYPE_PAID);

        if ($contestType === MatchContest::TYPE_FREE) {
            $this->merge([
                'joinprice' => $this->input('joinprice', 0),
            ]);
        }
    }

    public function rules(): array
    {
        return [
            'editid' => ['required', 'integer', 'exists:matchcobntests,id'],
            'contest_type' => ['required', Rule::in([MatchContest::TYPE_PAID, MatchContest::TYPE_FREE])],
            'matchesname' => ['required', 'string', 'max:150', Rule::unique('matchcobntests', 'contesttitile')->ignore($this->integer('editid'))],
            'prizetottalamount' => ['required', 'numeric', 'min:0'],
            'totalseat' => ['required', 'integer', 'min:1'],
            'winpertantage' => ['required', 'numeric', 'min:0', 'max:100'],
            'userenrery' => ['required', 'integer', 'min:1', 'max:99'],
            'joinprice' => ['required', 'numeric', 'min:0'],
            'prizedetail' => ['required', 'array', 'min:1'],
            'prizedetail.*' => ['required', 'numeric', 'min:0'],
            'prizestratseat' => ['required', 'array', 'min:1'],
            'prizestratseat.*' => ['required', 'integer', 'min:1'],
            'prizeendseat' => ['required', 'array', 'min:1'],
            'prizeendseat.*' => ['required', 'integer', 'min:1'],
        ];
    }

    public function after(): array
    {
        return [
            function (Validator $validator): void {
                $this->validatePrizeRanges($validator);
            },
        ];
    }

    private function validatePrizeRanges(Validator $validator): void
    {
        $prizeAmounts = array_values(array_filter((array) $this->input('prizedetail', []), fn ($value) => $value !== null && $value !== ''));
        $startSeats = array_values(array_filter((array) $this->input('prizestratseat', []), fn ($value) => $value !== null && $value !== ''));
        $endSeats = array_values(array_filter((array) $this->input('prizeendseat', []), fn ($value) => $value !== null && $value !== ''));

        if (count($prizeAmounts) !== count($startSeats) || count($startSeats) !== count($endSeats)) {
            $validator->errors()->add('prizedetail', 'Each reward row must include prize amount, seat start and seat end.');
            return;
        }

        $totalSeats = (int) $this->input('totalseat', 0);
        $lastEndSeat = 0;

        foreach ($startSeats as $index => $startSeat) {
            $endSeat = (int) ($endSeats[$index] ?? 0);
            $startSeat = (int) $startSeat;

            if ($startSeat > $endSeat) {
                $validator->errors()->add("prizestratseat.$index", 'Prize seat start must be less than or equal to prize seat end.');
            }

            if ($startSeat <= $lastEndSeat) {
                $validator->errors()->add("prizestratseat.$index", 'Prize seat ranges must be in increasing order without overlap.');
            }

            if ($totalSeats > 0 && $endSeat > $totalSeats) {
                $validator->errors()->add("prizeendseat.$index", 'Prize seat end cannot exceed total contest seats.');
            }

            $lastEndSeat = max($lastEndSeat, $endSeat);
        }
    }
}
