<?php

declare(strict_types=1);

namespace App\Schedules;

use Carbon\Carbon;

abstract class Schedule
{
    public static ?string $configKey = null;

    private static ?Carbon $start = null;

    private static ?Carbon $end = null;

    protected static function parseDate(string $key): ?Carbon
    {
        return rescue(
            fn () => Carbon::createFromFormat('Y-m-d', config(static::$configKey . '.' . $key))
        );
    }

    public static function start(): ?Carbon
    {
        if (
            null !== static::$configKey &&
            null === static::$start
        ) {
            static::$start = static::parseDate('start_date')?->startOfDay();
        }

        return static::$start;
    }

    public static function end(): ?Carbon
    {
        if (
            null !== static::$configKey &&
            null === static::$end
        ) {
            static::$end = static::parseDate('end_date')?->endOfDay();
        }

        return static::$end;
    }

    public static function isOpen(): bool
    {
        if (! static::start() || ! static::end()) {
            return false;
        }

        return now()->between(static::start(), static::end());
    }
}
