<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class StarRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    protected function prepareForValidation(): void
    {
        $merge = [];
        foreach (['country_id', 'facebook', 'twitter', 'instagram', 'star_dob'] as $field) {
            if ($this->has($field) && $this->input($field) === '') {
                $merge[$field] = null;
            }
        }
        if ($merge !== []) {
            $this->merge($merge);
        }

        if ($this->has('industries') && is_array($this->input('industries'))) {
            $clean = array_values(array_filter(
                $this->input('industries'),
                static fn ($v) => $v !== '' && $v !== null
            ));
            $this->merge(['industries' => $clean]);
        }
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'star_name' => 'required|string|max:50',
            'star_type' => 'required|string|in:actor,director,writer',
            'star_desc' => 'nullable|string|max:5000',
            'star_image' => 'nullable|file|mimes:jpg,jpeg,png,webp|max:20480',
            'slug' => 'nullable|string|max:191',
            'country_id' => 'nullable|integer|exists:countries,id',
            'star_dob' => 'nullable|date',
            'ranking' => 'nullable|string|max:191',
            'gender' => 'nullable|string|max:191',
            'industries' => 'nullable|array',
            'industries.*' => 'integer|exists:movie_industries,id',
            'facebook' => 'nullable|string|max:191|url',
            'twitter' => 'nullable|string|max:191|url',
            'instagram' => 'nullable|string|max:191|url',
        ];
    }

    /**
     * @return array<string, string>
     */
    public function attributes(): array
    {
        return [
            'star_name' => __('star_name'),
            'star_type' => __('star_type'),
            'star_desc' => __('star_bio'),
            'star_image' => __('Star Image (100x100)'),
            'country_id' => __('country_id'),
            'star_dob' => __('star_dob'),
            'ranking' => __('ranking'),
            'gender' => __('gender'),
            'industries' => __('industries'),
            'facebook' => __('facebook'),
            'twitter' => __('twitter(x)'),
            'instagram' => __('instagram'),
        ];
    }
}
