<?php

namespace App\Http\Requests\Admin\Master;

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

class ProductRequest extends FormRequest
{
    use HasProductVariantRules;

    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')],

            ...$this->productVariantRules(productId: $this->route('product')?->id),
        ];
    }

    /**
     * @return array<string, string>
     */
    public function attributes(): array
    {
        return [
            'name' => 'Nama Produk',
            'description' => 'Deskripsi',
            'category_ids' => 'Kategori',
            'category_ids.*' => 'Kategori',
            ...$this->productVariantAttributes(),
        ];
    }
}
