<?php

namespace Modules\Accounts\Services;

use Carbon\Carbon;
use Modules\Accounts\Models\FiscalYear;
use Modules\Accounts\Repositories\FiscalYearRepository;
use Modules\Core\Exceptions\ApiValidationException;
use Modules\Core\Exceptions\BusinessException;
use Modules\HR\DTO\HrSettingFilter;
use Termwind\Components\Hr;

class FiscalYearService
{
    public function __construct(
        protected FiscalYearRepository $fiscalYearRepo
    ) {}

    public function current(): ?FiscalYear
    {
        return $this->fiscalYearRepo->current();
    }

    public function detect(string|Carbon $date): FiscalYear
    {
        $fiscalYear = $this->fiscalYearRepo->findByDate($date);

        if (!$fiscalYear) {
            ApiValidationException::message(
                'No fiscal year found for the selected date.'
            );
        }

        if ($fiscalYear->is_closed) {
            BusinessException::message(
                'Fiscal year is closed.'
            );
        }

        if ($fiscalYear->is_locked) {
            BusinessException::message(
                'Fiscal year is locked.'
            );
        }

        return $fiscalYear;
    }

    public function ensureOpen(
        FiscalYear $fiscalYear,
        string|Carbon $transactionDate
    ): void {
        $transactionDate = Carbon::parse(
            $transactionDate
        );

        if ($fiscalYear->is_closed) {
            BusinessException::message('Fiscal year is closed.');
        }

        if ($fiscalYear->is_locked) {
            BusinessException::message('Fiscal year is locked.');
        }

        if ($fiscalYear->lock_date && $transactionDate->lte($fiscalYear->lock_date)) {
            BusinessException::message(
                sprintf(
                    'Transactions on or before %s are locked.',
                    $fiscalYear->lock_date->format('d M Y')
                )
            );
        }
    }

    public function clearCache(): void
    {
        $this->fiscalYearRepo->clearCache();
    }

    public function hrLookupList(HrSettingFilter $filter)
    {
        $columns = ['id', 'name','code','start_date','end_date'];
        return $this->fiscalYearRepo->all($filter, $columns);
    }
}
