<?php

namespace App\Http\Requests\Admin\Master;

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

class ProductRequest extends FormRequest
{
    use ValidatesMediaUploads;

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

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

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:200'],
            'description' => ['nullable', 'string'],

            'category_ids' => ['required', 'array', 'min:1'],
            'category_ids.*' => ['integer', Rule::exists('categories', 'id')->whereNull('deleted_at')],

            'variants' => ['required', 'array', 'min:1'],
            'variants.*.id' => [
                'nullable',
                'integer',
                Rule::exists('product_variants', 'id')
                    ->where('product_id', $this->route('product')?->id)
                    ->whereNull('deleted_at'),
            ],
            'variants.*.name' => ['required', 'string', 'max:200'],
            'variants.*.stock' => ['required', 'integer', 'min:0'],
            'variants.*.retail_stock' => ['required', 'integer', 'min:0'],
            ...$this->variantImageRules(),
        ];
    }

    /**
     * @return array<string, string>
     */
    public function attributes(): array
    {
        return [
            'name' => 'Nama Produk',
            'description' => 'Deskripsi',
            'category_ids' => 'Kategori',
            'category_ids.*' => 'Kategori',
            'variants' => 'Varian',
            'variants.*.name' => 'Nama Varian',
            'variants.*.stock' => 'Stok',
            'variants.*.retail_stock' => 'Stok Ecer',
            ...$this->variantImageAttributes('variants', 'Foto Varian'),
        ];
    }
}
