<?php

namespace App\Http\Requests;

use Illuminate\Support\Facades\Validator;

class DraftEnquirySubmissionRequest extends PartialEnquirySubmissionRequest
{
    #[\Override]
    protected function questionSpecificRules(): array
    {
        return [];
    }

    protected function passedValidation(): void
    {
        $form = $this->form();

        if (empty($form)) {
            return;
        }

        $validQuestions = collect($this->input('questions', []))
            ->filter(function ($answer, $questionId) use ($form) {
                $question = $form->questions->where('id', $questionId)->first();

                if (!$question || !$question->validation) {
                    return true;
                }

                $rules = $question->validation;
                $parts = is_string($rules) ? explode('|', $rules) : (array) $rules;
                $formatRules = array_values(
                    array_filter($parts, fn($r) => is_string($r) && $r !== 'required')
                );

                if (empty($formatRules)) {
                    return true;
                }

                return Validator::make(
                    ['value' => $answer],
                    ['value' => array_merge(['nullable'], $formatRules)]
                )->passes();
            })
            ->toArray();

        $this->merge(['questions' => $validQuestions]);
    }
}
