<?php

namespace App\Livewire\Forms\Studio\Master;

use App\Models\Formula;
use App\Rules\UnsignedInteger;
use Livewire\Form;

class FormulaForm extends Form
{
    public ?Formula $formula = null;

    public string $quality = '';

    public string $size = '';

    public string $volume = '';

    public function rules(): array
    {
        return [
            'quality' => ['required', 'string', 'max:20'],
            'size' => ['required', new UnsignedInteger],
            'volume' => ['required', new UnsignedInteger],
        ];
    }

    public function validationAttributes(): array
    {
        return [
            'quality' => 'kualitas',
            'size' => 'ukuran',
        ];
    }

    public function setFormula(Formula $formula)
    {
        $this->formula = $formula;

        $this->quality = $formula->quality;
        $this->size = $formula->size;
        $this->volume = replaceCurrency($formula->volume);
    }

    public function store()
    {
        $this->validate();

        return Formula::create($this->prepareSavedData());
    }

    public function update()
    {
        $this->validate();

        $this->formula->update($this->prepareSavedData());

        return $this->formula;
    }

    private function prepareSavedData()
    {
        return [
            'quality' => $this->quality,
            'size' => $this->size,
            'volume' => replaceCurrency($this->volume),
        ];
    }
}
