<?php

declare(strict_types=1);

namespace App\Http\Requests\Assignment;

use App\Enums\AssetCondition;
use App\Models\AssetAssignment;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

/**
 * Closes one open assignment. The legality check (still active) is
 * duplicated on purpose: it runs here, so the form shows a normal validation
 * error, and again inside AssignmentService::receiveReturn(), so the rule
 * still holds for any future caller that skips this request entirely.
 */
class StoreReturnRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user() !== null;
    }

    /**
     * @return array<string, array<int, mixed>>
     */
    public function rules(): array
    {
        return [
            'returned_at' => ['required', 'date', 'before_or_equal:today'],
            'condition_on_return' => ['required', Rule::enum(AssetCondition::class)],
            'return_notes' => ['nullable', 'string', 'max:2000'],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            $assignment = $this->targetAssignment();

            if (! $assignment->isActive()) {
                $validator->errors()->add('assignment', __('This assignment has already been returned.'));

                return;
            }

            $returnedAt = $this->date('returned_at');

            if ($returnedAt !== null && $returnedAt->lt($assignment->assigned_at->startOfDay())) {
                $validator->errors()->add('returned_at', __('The return date cannot be before the assigned date.'));
            }
        });
    }

    public function targetAssignment(): AssetAssignment
    {
        /** @var AssetAssignment $assignment */
        $assignment = $this->route('assignment');

        return $assignment;
    }

    protected function prepareForValidation(): void
    {
        $this->merge([
            'returned_at' => $this->filled('returned_at') ? $this->input('returned_at') : now()->toDateString(),
            'condition_on_return' => trim((string) $this->input('condition_on_return')),
            'return_notes' => $this->nullableString($this->input('return_notes')),
        ]);
    }

    private function nullableString(mixed $value): ?string
    {
        $value = trim((string) $value);

        return $value === '' ? null : $value;
    }
}
