<?php

namespace App\Livewire\Forms\Studio\Catalog;

use App\Models\Brand;
use App\Traits\Media\WithMediaHandler;
use App\Traits\Utilities\WithSortOrder;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Livewire\Form;

class BrandForm extends Form
{
    use WithMediaHandler, WithSortOrder;

    public ?Brand $brand = null;

    public string $name = '';

    public array $image = [];

    public function rules(): array
    {
        return [
            'name' => ['required', 'max:20', Rule::unique('brands', 'name')->whereNull('deleted_at')->ignore($this->brand)],
            'image' => 'array',
        ];
    }

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

    public function setBrand(Brand $brand): void
    {
        $this->brand = $brand;

        $this->name = $brand->name;

        $this->image = $this->mapMediaCollection($brand->getMedia('image'));
    }

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

        DB::transaction(function () {
            // Increment all existing brands' sort_order
            Brand::query()->increment('sort_order');

            $brand = Brand::create([
                'name' => $this->name,
                'sort_order' => 1,
            ]);

            $this->uploadMedia($this->image, $brand, 'image');
        });
    }

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

        DB::transaction(function () {
            $this->brand->update([
                'name' => $this->name,
            ]);

            $this->syncMedia($this->image, $this->brand, 'image');
            $this->uploadMedia($this->image, $this->brand, 'image');
        });
    }

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

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

    protected function getModelInstance(): Brand
    {
        return $this->brand;
    }
}
