<?php

namespace App\Http\Requests;

use App\Enums\FolderPriority;
use App\Enums\FolderStatus;
use App\Enums\FolderType;
use BenSampo\Enum\Rules\EnumValue;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

class StoreFolderRequest extends FormRequest
{
    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        $merge = [];

        if ($this->has('assigned_to') && $this->assigned_to === '') {
            $merge['assigned_to'] = null;
        }

        if ($this->filled('period_month') && (int) $this->period_month === 0) {
            $merge['period_month'] = null;
        }
        if ($this->filled('period_quarter') && (int) $this->period_quarter === 0) {
            $merge['period_quarter'] = null;
        }

        if ($merge !== []) {
            $this->merge($merge);
        }
    }

    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return $this->user() !== null;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $workspaceId = $this->session()->get('current_workspace_id');

        return [
            'client_id' => [
                'required',
                'integer',
                Rule::exists('clients', 'id')->where('workspace_id', $workspaceId),
            ],
            'title' => ['required', 'string', 'max:255'],
            'type' => ['required', new EnumValue(FolderType::class)],
            'period_year' => ['required', 'integer', 'min:2000', 'max:2100'],
            'period_month' => ['nullable', 'integer', 'min:1', 'max:12'],
            'period_quarter' => ['nullable', 'integer', 'min:1', 'max:4'],
            'due_date' => ['nullable', 'date'],
            'status' => ['nullable', Rule::in(FolderStatus::getValues())],
            'priority' => ['nullable', Rule::in(FolderPriority::getValues())],
            'assigned_to' => [
                'nullable',
                'integer',
                Rule::exists('users', 'id'),
            ],
            'notes_internal' => ['nullable', 'string', 'max:65535'],
            'notes_client' => ['nullable', 'string', 'max:65535'],
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            $type = $this->input('type');

            if ($type === 'vat') {
                $validator->errors()->add(
                    'type',
                    'Veuillez sélectionner TVA mensuelle ou TVA trimestrielle.',
                );
            }

            if ($type === 'vat_monthly') {
                $month = $this->input('period_month');
                if ($month === null || $month === '') {
                    $validator->errors()->add('period_month', 'Le mois est requis pour la TVA mensuelle.');
                }
                $this->merge(['period_quarter' => null]);
            }

            if ($type === 'vat_quarterly') {
                $quarter = $this->input('period_quarter');
                if ($quarter === null || $quarter === '') {
                    $validator->errors()->add('period_quarter', 'Le trimestre est requis pour la TVA trimestrielle.');
                }
                $this->merge(['period_month' => null]);
            }
        });
    }
}
