<?php

namespace App\Http\Requests\Admin\Master;

use App\Enums\Permission;
use App\Enums\RawMaterialUnit;
use App\Http\Requests\Concerns\ValidatesMediaUploads;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class RawMaterialRequest extends FormRequest
{
    use ValidatesMediaUploads;

    public function authorize(): bool
    {
        $permission = $this->isMethod('POST')
            ? Permission::RAW_MATERIALS_CREATE
            : Permission::RAW_MATERIALS_UPDATE;

        return $this->user()?->can($permission->value) ?? false;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:200'],
            'unit' => ['required', Rule::enum(RawMaterialUnit::class)],

            'prices' => ['required', 'array', 'min:1'],
            'prices.*.id' => [
                'nullable',
                'integer',
                Rule::exists('raw_material_prices', 'id')
                    ->where('raw_material_id', $this->route('rawMaterial')?->id)
                    ->whereNull('deleted_at'),
            ],
            'prices.*.variant' => ['required', 'string', 'max:200'],
            'prices.*.price' => ['required', 'integer', 'gt:0'],
            'prices.*.stock' => ['required', 'numeric', 'decimal:0,4', 'min:0'],
            ...$this->variantImageRules('prices'),
        ];
    }

    /**
     * @return array<string, string>
     */
    public function attributes(): array
    {
        return [
            'name' => 'Nama Bahan Baku',
            'unit' => 'Satuan',
            'prices' => 'Varian',
            'prices.*.variant' => 'Nama Varian',
            'prices.*.price' => 'Harga',
            'prices.*.stock' => 'Stok',
            ...$this->variantImageAttributes('prices', 'Foto Varian'),
        ];
    }
}
