<?php

declare(strict_types=1);

namespace App\Modules\Tenants\Services;

use App\Modules\Tenants\Models\Tenant;
use App\Support\TenantResolver;

class TenantService
{
    public function __construct(private readonly TenantResolver $tenantResolver)
    {
    }

    public function resolveFromHost(string $host): ?Tenant
    {
        $resolved = $this->tenantResolver->resolveFromHost($host);

        if ($resolved === null) {
            return null;
        }

        return new Tenant(
            id: $resolved['tenant_id'] ?? 'tenant-placeholder',
            tenantKey: $resolved['tenant_key'],
            name: ucfirst((string) $resolved['tenant_key']),
            status: 'active'
        );
    }

    /**
     * @return array<int, Tenant>
     */
    public function listTenants(): array
    {
        return array_map(
            static fn (array $tenant): Tenant => new Tenant(
                $tenant['id'],
                $tenant['tenant_key'],
                $tenant['name'],
                $tenant['status']
            ),
            $this->tenantPortfolio()
        );
    }

    /**
     * @return array<string, mixed>|null
     */
    public function findTenantById(string $tenantId): ?array
    {
        foreach ($this->tenantPortfolio() as $tenant) {
            if (($tenant['id'] ?? '') === $tenantId) {
                return $tenant;
            }
        }

        return null;
    }

    /**
     * @return array<string, mixed>|null
     */
    public function findTenantByKey(string $tenantKey): ?array
    {
        foreach ($this->tenantPortfolio() as $tenant) {
            if (($tenant['tenant_key'] ?? '') === $tenantKey) {
                return $tenant;
            }
        }

        return null;
    }

    /**
     * @return array<string, mixed>
     */
    public function adminOverview(): array
    {
        $portfolio = $this->tenantPortfolio();
        $activeCount = count(array_filter($portfolio, static fn (array $tenant): bool => $tenant['status'] === 'active'));
        $memberCount = array_sum(array_map(static fn (array $tenant): int => $tenant['member_count'], $portfolio));
        $providerCount = array_sum(array_map(static fn (array $tenant): int => $tenant['oidc_provider_count'], $portfolio));

        return [
            'metrics' => [
                [
                    'label' => 'Aktive Tenants',
                    'value' => (string) $activeCount,
                    'detail' => 'Mandanten mit aktivem Produktbetrieb und freigeschalteter Plattform.',
                ],
                [
                    'label' => 'Mitglieder gesamt',
                    'value' => (string) $memberCount,
                    'detail' => 'Alle aktiven Nutzerzuordnungen ueber die Mandantenlandschaft.',
                ],
                [
                    'label' => 'SSO-Abdeckung',
                    'value' => (string) $providerCount,
                    'detail' => 'Lokale Anmeldung plus ADFS/OIDC fuer zentrale oder tenantbezogene Anmeldung.',
                ],
                [
                    'label' => 'Betriebsstatus',
                    'value' => 'Stabil',
                    'detail' => 'Queues, Exporte und Benachrichtigungen sind fuer Cron-Betrieb vorbereitet.',
                ],
            ],
            'tenants' => $portfolio,
            'shared_access' => [
                [
                    'email' => 'leitung@kaffeeliste.example',
                    'tenants' => ['Werk Berlin', 'Werk Koeln', 'Shared Services'],
                    'next_step' => 'Tenant-Auswahl vor lokaler Anmeldung oder ADFS/OIDC anzeigen',
                    'status' => 'mehrfach',
                ],
                [
                    'email' => 'mia@berlin.example',
                    'tenants' => ['Werk Berlin'],
                    'next_step' => 'Direkt an den Tenant-Login weiterleiten',
                    'status' => 'einzeln',
                ],
                [
                    'email' => 'extern@example.org',
                    'tenants' => [],
                    'next_step' => 'Kontakt zum Tenant-Admin oder zentrale Einladung anbieten',
                    'status' => 'unbekannt',
                ],
            ],
            'operations' => [
                [
                    'title' => 'Neuen Tenant live schalten',
                    'detail' => 'Domain, Initial-Admin, Branding und Importpfad in einem zentralen Rollout steuern.',
                    'state' => 'Bereit',
                ],
                [
                    'title' => 'Mitglieder zentral pruefen',
                    'detail' => 'Mehrfachzuordnungen und offene Tenant-Einladungen vor Freischaltung abstimmen.',
                    'state' => 'Im Fokus',
                ],
                [
                    'title' => 'SSO-Rollout konsolidieren',
                    'detail' => 'Provider, Redirect-URIs und Fallback-Login tenantweise vereinheitlichen.',
                    'state' => 'In Arbeit',
                ],
            ],
        ];
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    public function lookupTenantsByEmail(string $email): array
    {
        $normalized = strtolower(trim($email));

        $directory = [
            'mia@berlin.example' => ['berlin'],
            'leitung@kaffeeliste.example' => ['berlin', 'koeln', 'shared-services'],
            'ops@kaffeeliste.example' => ['shared-services', 'finance-hub'],
        ];

        $matches = $directory[$normalized] ?? [];
        $portfolio = [];

        foreach ($this->tenantPortfolio() as $tenant) {
            if (in_array($tenant['tenant_key'], $matches, true)) {
                $portfolio[] = $tenant;
            }
        }

        return $portfolio;
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    public function tenantPortfolio(): array
    {
        return [
            [
                'id' => 'tenant-berlin',
                'tenant_key' => 'berlin',
                'name' => 'Werk Berlin',
                'status' => 'active',
                'domain' => 'berlin.kaffeeliste.de',
                'member_count' => 42,
                'admin_count' => 4,
                'oidc_provider_count' => 1,
                'tenant_health' => 'stabil',
                'billing_state' => 'aktiv',
                'login_mode' => 'Lokal + ADFS/OIDC',
                'primary_contact' => 'Office Operations Berlin',
            ],
            [
                'id' => 'tenant-koeln',
                'tenant_key' => 'koeln',
                'name' => 'Werk Koeln',
                'status' => 'active',
                'domain' => 'koeln.kaffeeliste.de',
                'member_count' => 31,
                'admin_count' => 3,
                'oidc_provider_count' => 1,
                'tenant_health' => 'stabil',
                'billing_state' => 'aktiv',
                'login_mode' => 'Lokal + ADFS/OIDC',
                'primary_contact' => 'Backoffice Koeln',
            ],
            [
                'id' => 'tenant-shared-services',
                'tenant_key' => 'shared-services',
                'name' => 'Shared Services',
                'status' => 'active',
                'domain' => 'shared.kaffeeliste.de',
                'member_count' => 18,
                'admin_count' => 2,
                'oidc_provider_count' => 2,
                'tenant_health' => 'stabil',
                'billing_state' => 'aktiv',
                'login_mode' => 'Lokal + ADFS/OIDC',
                'primary_contact' => 'Platform Operations',
            ],
            [
                'id' => 'tenant-finance-hub',
                'tenant_key' => 'finance-hub',
                'name' => 'Finance Hub',
                'status' => 'sandbox',
                'domain' => 'finance.kaffeeliste.de',
                'member_count' => 9,
                'admin_count' => 2,
                'oidc_provider_count' => 0,
                'tenant_health' => 'boarding',
                'billing_state' => 'test',
                'login_mode' => 'Lokal + ADFS/OIDC',
                'primary_contact' => 'Finance Enablement',
            ],
        ];
    }
}
