<?php

namespace App\Http\Requests\Admin\Manage;

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

class CuttingRequest extends FormRequest
{
    use ValidatesMediaUploads;

    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',
                Rule::exists('raw_material_prices', 'id')->whereNull('deleted_at'),
            ];
            $rules['materials.*.material_usage'] = ['required', 'numeric', 'decimal:0,4', 'gt:0'];
            $rules['materials.*.material_result'] = ['nullable', 'integer', 'min:0'];
            $rules['materials.*.combination_id'] = ['nullable', 'integer'];
            $rules['materials.*.combination_material_result'] = ['nullable', 'integer', 'min:0'];
        }

        $rules['results'] = ['required', 'array', 'min:1'];
        $rules['results.*.product_name'] = ['required', 'string', 'max:255'];

        $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 array_merge(
            $rules,
            $this->photoRules('photos', 10),
        );
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            $errors = $validator->errors();

            foreach ($this->input('materials', []) as $index => $material) {
                $key = "materials.{$index}.raw_material_price_id";

                if ($errors->has($key)) {
                    Log::warning('Validasi varian bahan baku gagal', [
                        'index' => $index,
                        'raw_material_price_id' => $material['raw_material_price_id'] ?? null,
                        'error' => $errors->first($key),
                    ]);
                }
            }
        });
    }

    /**
     * @return array<string, string>
     */
    public function attributes(): array
    {
        return array_merge(
            [
                'description' => 'keterangan',
                'materials' => 'bahan baku',
                'materials.*.raw_material_price_id' => 'varian',
                'materials.*.material_usage' => 'pemakaian',
                'materials.*.material_result' => 'hasil',
                'materials.*.combination_material_result' => 'hasil kombinasi',
                'results' => 'hasil produk',
                'results.*.product_name' => 'nama produk',
                'results.*.cutting_result' => 'hasil',
                'results.*.sample' => 'sample',
                'results.*.original_outside_sample' => 'diluar sample',
                'sewing_cost' => 'jasa jahit',
                'other_cost' => 'biaya lainnya',
            ],
            $this->photoUploadAttributes('foto cutting'),
        );
    }
}
