<?php

namespace App\Http\Requests\Admin\Manage;

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

class PurchaseRequest extends FormRequest
{
    use ValidatesMediaUploads;

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

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

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $rules = [
            'supplier_id' => ['required', 'integer', Rule::exists('suppliers', 'id')->whereNull('deleted_at')],
            'discount' => ['nullable', 'integer', 'min:0'],
            'shipping_cost' => ['nullable', 'integer', 'min:0'],
            'notes' => ['nullable', 'string', 'max:100'],
            ...$this->photoRules(),
        ];

        if ($this->isMethod('PUT') || $this->isMethod('PATCH')) {
            $rules['items'] = ['required', 'array', 'min:1'];
            $rules['items.*.raw_material_price_id'] = [
                'required',
                'integer',
                Rule::exists('raw_material_prices', 'id')->whereNull('deleted_at'),
            ];
            $rules['items.*.quantity'] = ['required', 'numeric', 'decimal:0,4', 'gt:0'];
        }

        return $rules;
    }

    /**
     * @return array<string, string>
     */
    public function attributes(): array
    {
        return [
            'supplier_id' => 'Supplier',
            'discount' => 'Diskon',
            'shipping_cost' => 'Ongkir',
            'notes' => 'Keterangan',
            'items' => 'Bahan Baku',
            'items.*.raw_material_price_id' => 'Bahan Baku',
            'items.*.quantity' => 'Jumlah',
            ...$this->photoUploadAttributes('Bukti Transaksi'),
        ];
    }
}
