<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ExpenseCategory extends Model
{
    protected $fillable = [
        'company_id', 'name', 'is_active',
    ];

    protected $casts = [
        'is_active' => 'boolean',
    ];

    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }

    public static function ensureDefaultsForCompany(int $companyId): void
    {
        foreach (config('expense.default_categories', []) as $name) {
            static::firstOrCreate(
                ['company_id' => $companyId, 'name' => $name],
                ['is_active' => true]
            );
        }
    }

    /**
     * @return list<array{id: int|null, name: string}>
     */
    public static function pickerListForCompany(int $companyId): array
    {
        static::ensureDefaultsForCompany($companyId);

        return static::where('company_id', $companyId)
            ->where('is_active', true)
            ->orderBy('name')
            ->get(['id', 'name'])
            ->map(fn ($c) => ['id' => $c->id, 'name' => $c->name])
            ->values()
            ->all();
    }
}
