<?php

declare(strict_types=1);

namespace App\Modules\Identity\Services;

use App\Modules\Tenants\Services\TenantService;

class AuthService
{
    public function __construct(private readonly TenantService $tenantService)
    {
    }

    public function availableProviders(): array
    {
        return [
            'password' => [
                'label' => 'Zentraler Passwort-Login',
                'type' => 'password',
            ],
            'oidc' => [
                'label' => 'SSO via OIDC',
                'type' => 'oidc',
            ],
        ];
    }

    /**
     * @return array<string, mixed>
     */
    public function centralLoginPreview(): array
    {
        $singleEmail = 'mia@berlin.example';
        $multipleEmail = 'leitung@kaffeeliste.example';
        $unknownEmail = 'extern@example.org';

        return [
            'single' => [
                'email' => $singleEmail,
                'status' => 'redirect-tenant',
                'matches' => $this->tenantService->lookupTenantsByEmail($singleEmail),
                'message' => 'Bei genau einem Treffer wird direkt in den zugeordneten Tenant weitergeleitet.',
            ],
            'multiple' => [
                'email' => $multipleEmail,
                'status' => 'select-tenant',
                'matches' => $this->tenantService->lookupTenantsByEmail($multipleEmail),
                'message' => 'Bei mehreren Trefferkonten erscheint zuerst eine Tenant-Auswahl fuer denselben Mitarbeiter.',
            ],
            'unknown' => [
                'email' => $unknownEmail,
                'status' => 'request-tenant',
                'matches' => [],
                'message' => 'Unbekannte Mail-Adressen werden nicht ins Leere geleitet, sondern klar auf Tenant- oder Admin-Kontakt gefuehrt.',
            ],
        ];
    }

    public function attemptLogin(array $payload): array
    {
        $email = strtolower(trim((string) ($payload['email'] ?? '')));
        $matches = $this->tenantService->lookupTenantsByEmail($email);

        if (count($matches) === 1) {
            $tenant = $matches[0];

            return [
                'status' => 'redirect-tenant',
                'email' => $email,
                'tenant' => $tenant,
                'redirect_to' => 'https://' . $tenant['domain'] . '/login',
            ];
        }

        if (count($matches) > 1) {
            return [
                'status' => 'select-tenant',
                'email' => $email,
                'tenants' => $matches,
            ];
        }

        return [
            'status' => 'request-tenant',
            'email' => $email !== '' ? $email : null,
        ];
    }
}
