<?php

namespace App\Support;

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

final class AgentSettlementSiteTimezone
{
    public static function forSiteId(int $adminSiteId): string
    {
        return self::normalize((string) (DB::table('admin_sites')
            ->where('id', $adminSiteId)
            ->value('settlement_timezone') ?? ''));
    }

    public static function forSiteCode(string $siteCode): string
    {
        return self::normalize((string) (DB::table('admin_sites')
            ->where('code', $siteCode)
            ->value('settlement_timezone') ?? ''));
    }

    public static function isValid(?string $timezone): bool
    {
        return is_string($timezone)
            && $timezone !== ''
            && in_array($timezone, timezone_identifiers_list(), true);
    }

    public static function localDayFromUtc(mixed $instant, string $timezone): string
    {
        return Carbon::parse((string) $instant, 'UTC')
            ->timezone($timezone)
            ->toDateString();
    }

    private static function normalize(?string $timezone): string
    {
        if (self::isValid($timezone)) {
            return (string) $timezone;
        }

        $fallback = (string) config('lottery.settlement.default_timezone', config('app.timezone', 'UTC'));

        return self::isValid($fallback) ? $fallback : 'UTC';
    }
}
