<?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
    {
        return [
            '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('photos', 1),

            'items' => ['required', 'array', 'min:1'],
            'items.*.raw_material_price_id' => ['nullable', 'integer'],
            'items.*.name' => ['required', 'string', 'max:200'],
            'items.*.unit' => ['required', 'string', Rule::in(['yard', 'meter', 'kilogram'])],
            'items.*.variant' => ['required', 'string', 'max:200'],
            'items.*.quantity' => ['required', 'numeric', 'decimal:0,4', 'gt:0'],
            'items.*.price' => ['required', 'integer', 'gt:0'],
            'items.*.photos' => ['nullable', 'array', 'max:5'],
            'items.*.photos.*' => ['image', 'mimes:jpg,jpeg,png,webp', 'max:5120'],
            ...$this->variantImageRules('items', 5),
        ];
    }

    /**
     * @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.*.name' => 'nama bahan baku',
            'items.*.unit' => 'satuan',
            'items.*.variant' => 'nama varian',
            'items.*.quantity' => 'jumlah',
            'items.*.price' => 'harga',
            ...$this->photoUploadAttributes('bukti transaksi', 'photos'),
            ...$this->variantImageAttributes('items', 'foto varian'),
        ];
    }
}
