<?php

namespace App\Http\Requests\Api\Auth;

use App\Models\KycForm;
use Illuminate\Foundation\Http\FormRequest;

class UserKycRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return auth('client')->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 array_merge($this->personalDetailsRules(), $this->kycFormsRules());
    }

    private function personalDetailsRules()
    {
        return [
            'city' => 'required|string|max:191',
            'state' => 'required|string|max:191',
            'country' => 'required|string|max:191',
            'address' => 'required|string|max:500',
            'zip_code' => 'required|string|max:191',
        ];
    }

    private function kycFormsRules()
    {
        $validation = [];
        $kyc_forms = KycForm::orderBy('position', 'asc')->get();

        foreach ($kyc_forms as $kyc_form) {
            $validation['fields.'.$kyc_form->id] = [
                $kyc_form->required ? 'required' : 'nullable',
                ...$this->getFileValidation($kyc_form->field_type),
                $kyc_form->field_type == 'select' ? 'in:'.implode(',', $kyc_form->options) : '',
            ];
        }

        return $validation;
    }

    private function getFileValidation($type): array
    {
        if ($type === 'file') {
            return ['mimes:pdf,doc', 'max:2048'];
        }

        if ($type === 'image') {
            return ['image', 'mimes:jpg,png,jpeg', 'max:2048'];
        }

        if (in_array($type, ['text', 'textarea', 'select'])) {
            return ['string', 'max:256'];
        }

        return [];
    }
}
