<?php

namespace Modules\Accounts\Repositories;

use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Modules\Accounts\Models\AccountingPeriod;

class AccountingPeriodRepository
{
    public function current(): ?AccountingPeriod
    {
        return Cache::remember(
            'current_accounting_period',
            now()->addHour(),
            fn () => AccountingPeriod::query()
                ->current()
                ->open()
                ->first()
        );
    }

    public function find(int $id): ?AccountingPeriod
    {
        return AccountingPeriod::find($id);
    }

    public function findByDate(string|Carbon $date, ?int $fyId = null): ?AccountingPeriod
    {
        return AccountingPeriod::query()
            ->when($fyId, function ($query, $fyId) {
                return $query->where('fiscal_year_id', $fyId);
            })
            ->byDate($date)
            ->first();
    }

    public function openByDate(string|Carbon $date, ?int $fyId = null): ?AccountingPeriod
    {
        return AccountingPeriod::query()
            ->when($fyId, function ($query, $fyId) {
                return $query->where('fiscal_year_id', $fyId);
            })
            ->byDate($date)
            ->open()
            ->first();
    }

    public function clearCache(): void
    {
        Cache::forget('current_accounting_period');
    }
}
