<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class UpdateImportMap extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'data.source_type' => ['sometimes', 'nullable', 'string', Rule::in(['file', 'http_json'])],
            'data.update_only' => ['sometimes', 'nullable', 'boolean'],

            // HTTP/JSON source — only required when source_type is http_json.
            'data.http' => ['sometimes', 'nullable', 'array'],
            'data.http.url' => [
                Rule::requiredIf(fn () => $this->input('data.source_type') === 'http_json'),
                'nullable',
                'url',
            ],
            'data.http.headers' => ['sometimes', 'nullable', 'array'],
            'data.http.headers.*.key' => ['required_with:data.http.headers.*.value', 'nullable', 'string'],
            'data.http.headers.*.value' => ['nullable', 'string'],
            'data.http.array_path' => ['sometimes', 'nullable', 'string'],
            'data.http.latest_by' => ['sometimes', 'nullable', 'string'],
        ];
    }

    /**
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'data.http.url.required_if' => 'A URL is required when the source type is HTTP API (JSON).',
            'data.http.url.url' => 'The URL must be a valid HTTP/HTTPS URL.',
            'data.http.headers.*.key.required_with' => 'Each header row needs a name (e.g. x-api-key) when a value is set.',
        ];
    }
}
