<?php

namespace App\Domain\Accounting\Models;

use App\Domain\Accounting\Enums\PeriodStatus;
use App\Support\Concerns\HasUuid;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/** One accounting period (§46). */
class FinancialPeriod extends Model
{
    use HasUuid;

    protected $guarded = ['id', 'uuid'];

    protected function casts(): array
    {
        return [
            'status' => PeriodStatus::class,
            'starts_on' => 'date',
            'ends_on' => 'date',
            'closed_at' => 'datetime',
            'reopened_at' => 'datetime',
        ];
    }

    public function year(): BelongsTo
    {
        return $this->belongsTo(FinancialYear::class, 'financial_year_id');
    }

    public function contains(string $date): bool
    {
        return $date >= $this->starts_on->toDateString() && $date <= $this->ends_on->toDateString();
    }

    /** The period a date falls in, if the company has defined one. */
    public function scopeCovering(Builder $query, int $companyId, string $date): Builder
    {
        return $query->where('company_id', $companyId)
            ->whereDate('starts_on', '<=', $date)
            ->whereDate('ends_on', '>=', $date);
    }
}
