<?php

namespace App\Http\Requests\Admin\Manage;

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

class CuttingRequest extends FormRequest
{
    public function authorize(): bool
    {
        $permission = $this->isMethod('POST')
            ? Permission::CUTTINGS_CREATE
            : Permission::CUTTINGS_UPDATE;

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

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $isCreate = $this->isMethod('POST');

        $rules = [
            'description' => ['nullable', 'string', 'max:100'],

            'sewing_cost' => ['nullable', 'integer', 'min:0'],
            'other_cost' => ['nullable', 'integer', 'min:0'],
        ];

        if (! $isCreate) {
            $rules['materials'] = ['required', 'array', 'min:1'];
            $rules['materials.*.raw_material_price_id'] = [
                'required',
                'integer',
                'distinct',
                Rule::exists('raw_material_prices', 'id')->whereNull('deleted_at'),
            ];
            $rules['materials.*.material_usage'] = ['required', 'numeric', 'decimal:0,4', 'gt:0'];

            $rules['results'] = ['required', 'array', 'min:1'];
            $rules['results.*.product_variant_id'] = [
                'required',
                'integer',
                'distinct',
                Rule::exists('product_variants', 'id')->whereNull('deleted_at'),
            ];
            $rules['results.*.cutting_result'] = ['required', 'integer', 'min:1'];
            $rules['results.*.sample'] = ['required', 'integer', 'min:0'];
            $rules['results.*.original_outside_sample'] = ['required', 'integer', 'min:0'];
        }

        return $rules;
    }

    /**
     * @return array<string, string>
     */
    public function attributes(): array
    {
        return [
            'description' => 'Keterangan',
            'materials' => 'Bahan Baku',
            'materials.*.raw_material_price_id' => 'Bahan Baku',
            'materials.*.material_usage' => 'Pemakaian',
            'results' => 'Hasil Produk',
            'results.*.product_variant_id' => 'Varian Produk',
            'results.*.cutting_result' => 'Hasil',
            'results.*.sample' => 'sample',
            'results.*.original_outside_sample' => 'Diluar sample',
            'sewing_cost' => 'Jasa Jahit',
            'other_cost' => 'Biaya Lainnya',
        ];
    }
}
