<?php

namespace App\Http\Requests\Admin\Manage;

use App\Concerns\CurrencyStripping;
use App\Enums\RawMaterialUnit;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class PurchaseRequest extends FormRequest
{
    use CurrencyStripping;

    public function authorize(): bool
    {
        return true;
    }

    public function prepareForValidation(): void
    {
        $this->merge($this->stripCurrencyDot($this->all(), 'variants.*.price', 'discount', 'shipping_cost'));
    }

    public function rules(): array
    {
        return [
            'mode' => ['sometimes', 'required', 'in:new,existing'],
            'name' => ['required_unless:mode,existing', 'string', 'max:200'],
            'unit' => [$this->isMethod('post') ? 'required_unless:mode,existing' : 'nullable', Rule::in(RawMaterialUnit::values())],
            'variants' => ['required_unless:mode,existing', 'array', 'min:1'],
            'variants.*.variant' => ['required_unless:mode,existing', 'string', 'max:200'],
            'variants.*.price' => ['required_unless:mode,existing', 'integer', 'min:0'],
            'variants.*.stock' => ['required_unless:mode,existing', 'integer', 'min:0'],
            'variants.*.photo_key' => ['required_unless:mode,existing', 'string', 'max:500'],
            'existing_items' => ['required_if:mode,existing', 'array', 'min:1'],
            'existing_items.*.raw_material_price_id' => ['required', 'integer', 'exists:raw_material_prices,id'],
            'existing_items.*.quantity' => ['required', 'integer', 'min:1'],
            'existing_items.*.unit_price' => ['required', 'integer', 'min:0'],
            'supplier_id' => ['required', 'integer', 'exists:suppliers,id'],
            'discount' => ['nullable', 'integer', 'min:0'],
            'shipping_cost' => ['nullable', 'integer', 'min:0'],
            'notes' => ['nullable', 'string', 'max:100'],
            'photo_key' => ['nullable', 'string', 'max:500'],
        ];
    }

    public function attributes(): array
    {
        return [
            'name' => 'Nama Bahan Baku',
            'unit' => 'Satuan',
            'variants' => 'Varian',
            'variants.*.variant' => 'Nama Varian',
            'variants.*.price' => 'Harga',
            'variants.*.stock' => 'Stok',
            'variants.*.photo_key' => 'Foto Varian',
            'existing_items' => 'Item Bahan Baku',
            'existing_items.*.raw_material_price_id' => 'Varian Bahan Baku',
            'existing_items.*.quantity' => 'Jumlah',
            'existing_items.*.unit_price' => 'Harga Beli',
            'supplier_id' => 'Supplier',
            'discount' => 'Diskon',
            'shipping_cost' => 'Ongkir',
            'notes' => 'Keterangan',
            'photo_key' => 'Foto',
        ];
    }
}
