<?php

namespace App\Livewire\Forms\Studio\Loyalty;

use App\Models\Tier;
use App\Rules\UnsignedInteger;
use Illuminate\Support\Facades\DB;
use Livewire\Form;

class TierForm extends Form
{
    public ?Tier $tier = null;

    public string $name = '';

    public string $min_spending = '';

    public ?string $max_spending = null;

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:50'],
            'min_spending' => ['required', new UnsignedInteger],
            'max_spending' => ['nullable', new UnsignedInteger, 'gte:min_spending'],
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            $minSpending = parseRupiahToInt($this->min_spending);
            $maxSpending = $this->max_spending ? parseRupiahToInt($this->max_spending) : null;
            $ignoreId = $this->tier?->id;

            $tierErrors = Tier::validateTierPoints($minSpending, $maxSpending, $ignoreId);

            foreach ($tierErrors as $error) {
                $validator->errors()->add('min_spending', $error);
            }
        });
    }

    public function validationAttributes(): array
    {
        return [
            'name' => 'nama',
            'min_spending' => 'min. belanja',
            'max_spending' => 'maks. belanja',
        ];
    }

    public function setTier(Tier $tier): void
    {
        $this->tier = $tier;

        $this->name = $tier->name;
        $this->min_spending = formatCurrencyNumber($tier->min_spending);
        $this->max_spending = $tier->max_spending ? formatCurrencyNumber($tier->max_spending) : null;
    }

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

        DB::transaction(function () {
            Tier::create($this->prepareSavedData());
        });
    }

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

        DB::transaction(function () {
            $this->tier->update($this->prepareSavedData());

            $this->tier;
        });
    }

    private function prepareSavedData(): array
    {
        return [
            'name' => $this->name,
            'min_spending' => parseRupiahToInt($this->min_spending),
            'max_spending' => parseRupiahToInt($this->max_spending),
        ];
    }
}
