<?php

namespace App\Livewire\Forms\Studio\Feature;

use App\Models\PerfumeFeature;
use App\Traits\Utilities\WithSortOrder;
use Illuminate\Support\Facades\DB;
use Livewire\Form;

class PerfumeFeatureForm extends Form
{
    use WithSortOrder;

    public ?PerfumeFeature $perfumeFeature = null;

    public string $name = '';

    public string $description = '';

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:50'],
            'description' => ['required', 'string'],
        ];
    }

    public function validationAttributes(): array
    {
        return [
            'name' => 'nama',
            'description' => 'keterangan',
        ];
    }

    public function setPerfumeFeature(PerfumeFeature $perfumeFeature): void
    {
        $this->perfumeFeature = $perfumeFeature;

        $this->name = $perfumeFeature->name;
        $this->description = $perfumeFeature->description;
    }

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

        DB::transaction(function () {
            // Increment all existing perfume features' sort_order
            PerfumeFeature::query()->increment('sort_order');

            PerfumeFeature::create([
                'name' => $this->name,
                'description' => $this->description,
                'sort_order' => 1,
            ]);
        });
    }

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

        $this->perfumeFeature->update([
            'name' => $this->name,
            'description' => $this->description,
        ]);
    }

    public function delete(): void
    {
        $this->perfumeFeature->delete();
        $this->adjustSortOrderAfterDelete($this->perfumeFeature);
    }

    protected function getModelClass(): string
    {
        return PerfumeFeature::class;
    }

    protected function getModelInstance(): PerfumeFeature
    {
        return $this->perfumeFeature;
    }
}
