<?php

declare(strict_types=1);

namespace App\Services\Alerts;

use App\Models\Workspace;
use App\Models\WorkspaceSetting;

class WorkspaceTimezoneResolver
{
    public function resolve(Workspace $workspace): string
    {
        $candidates = [
            $this->normalizeTimezone($workspace->getAttribute('timezone')),
            $this->settingTimezone($workspace, 'alerts', 'timezone'),
            $this->settingTimezone($workspace, 'workspace', 'timezone'),
            $this->settingTimezone($workspace, 'general', 'timezone'),
            $this->normalizeTimezone(config('app.timezone')),
        ];

        foreach ($candidates as $candidate) {
            if ($candidate !== null) {
                return $candidate;
            }
        }

        return 'UTC';
    }

    private function settingTimezone(Workspace $workspace, string $domain, string $key): ?string
    {
        $setting = WorkspaceSetting::query()
            ->where('workspace_id', (int) $workspace->getKey())
            ->where('domain', $domain)
            ->where('key', $key)
            ->first(['value']);

        if (! $setting instanceof WorkspaceSetting) {
            return null;
        }

        return $this->normalizeTimezone($setting->getAttribute('value'));
    }

    private function normalizeTimezone(mixed $value): ?string
    {
        if (is_array($value)) {
            $value = $value['timezone'] ?? null;
        }

        if (! is_string($value)) {
            return null;
        }

        $value = trim($value);

        if ($value === '') {
            return null;
        }

        if (! in_array($value, \DateTimeZone::listIdentifiers(), true)) {
            return null;
        }

        return $value;
    }
}
