<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class BillingPeriod extends Model
{
    use HasFactory;

    protected $fillable = ['year', 'month', 'start_date', 'end_date', 'status'];

    protected $casts = [
        'year' => 'integer',
        'month' => 'integer',
        'start_date' => 'date',
        'end_date' => 'date',
    ];

    public function charges(): HasMany
    {
        return $this->hasMany(LineBillingCharge::class);
    }

    public function label(): string
    {
        return period_label($this->year, $this->month);
    }

    public function key(): string
    {
        return sprintf('%04d-%02d', $this->year, $this->month);
    }

    public static function findOrCreatePeriod(int $year, int $month): self
    {
        $start = \Carbon\Carbon::createFromDate($year, $month, 1)->startOfMonth();
        $end = $start->copy()->endOfMonth();

        return static::query()->firstOrCreate(
            ['year' => $year, 'month' => $month],
            ['start_date' => $start->toDateString(), 'end_date' => $end->toDateString(), 'status' => 'open']
        );
    }
}
