<?php

namespace App\Http\Requests;

use App\Models\Inspection;
use App\Models\InspectionTemplate;
use Illuminate\Foundation\Http\FormRequest;

class InspectionUpdateRequest extends FormRequest
{
    public function authorize(): bool
    {
        $inspection = $this->route('inspection') ?? Inspection::find($this->route('inspection'));
        if ($inspection) {
            return $this->user()->can('edit inspections', $inspection->project) && $this->user()->can('edit', $inspection);
        }
        return $this->user()->can('edit inspections');
    }

    public function rules(): array
    {
        return [
            'selectedTemplateId' => 'required|exists:inspection_templates,id',
            'editInspectionPhotos.*' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:10240',
            'editInspectionPhotosToDelete' => 'array',
            'editInspectionPhotosToDelete.*' => 'exists:media,id',
            'editInspectionFormData' => 'nullable|array',
            'editInspectionResult' => 'nullable|in:pass,fail',
            'editInspectionNotes' => 'nullable|string',
        ];
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $template = InspectionTemplate::find($this->input('selectedTemplateId'));
            if ($template) {
                foreach ($template->fields as $field) {
                    if (($field['required'] ?? false) && empty($this->input("editInspectionFormData.{$field['name']}"))) {
                        $validator->errors()->add(
                            "editInspectionFormData.{$field['name']}",
                            "El campo {$field['label']} es obligatorio."
                        );
                    }
                }
            }
        });
    }
}