<?php

namespace App\Models;

use App\Concerns\RecordsCreator;
use App\Support\ExpenseCategoryLabels;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ExpenseCategory extends Model
{
    use RecordsCreator;

    /**
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'slug',
        'description',
        'is_active',
        'updated_by',
    ];

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
        ];
    }

    /**
     * @return BelongsTo<User, $this>
     */
    public function updater(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    /**
     * @return HasMany<Expense, $this>
     */
    public function expenses(): HasMany
    {
        return $this->hasMany(Expense::class);
    }

    public function displayName(): string
    {
        return ExpenseCategoryLabels::label($this->slug, $this->name);
    }

    /**
     * @return list<array{id: int, name: string, slug: string|null, description: string|null, is_active: bool}>
     */
    public static function optionsForForm(): array
    {
        return self::query()
            ->where('is_active', true)
            ->orderBy('name')
            ->get(['id', 'name', 'slug', 'description', 'is_active'])
            ->map(fn (self $category): array => [
                'id' => $category->id,
                'name' => $category->displayName(),
                'slug' => $category->slug,
                'description' => $category->description,
                'is_active' => $category->is_active,
            ])
            ->values()
            ->all();
    }
}
