<?php

declare(strict_types=1);

namespace App\Services\Auth;

use App\Models\ManagedEnvironment;
use App\Models\ManagedEnvironmentMembership;
use App\Models\User;
use App\Services\Intune\AuditLogger;
use App\Support\Audit\AuditActionId;
use Illuminate\Support\Facades\DB;

class ManagedEnvironmentDiagnosticsService
{
    public function __construct(public AuditLogger $auditLogger) {}

    public function tenantHasNoOwners(ManagedEnvironment $tenant): bool
    {
        return false;
    }

    public function userHasDuplicateMemberships(ManagedEnvironment $tenant, User $user): bool
    {
        return ManagedEnvironmentMembership::query()
            ->where('managed_environment_id', (int) $tenant->getKey())
            ->where('user_id', (int) $user->getKey())
            ->count() > 1;
    }

    public function mergeDuplicateMembershipsForUser(ManagedEnvironment $tenant, User $actor, User $member): void
    {
        DB::transaction(function () use ($tenant, $actor, $member): void {
            $memberships = ManagedEnvironmentMembership::query()
                ->where('managed_environment_id', (int) $tenant->getKey())
                ->where('user_id', (int) $member->getKey())
                ->orderBy('created_at')
                ->get();

            if ($memberships->count() <= 1) {
                return;
            }

            $membershipToKeep = $memberships->first();
            if (! $membershipToKeep instanceof ManagedEnvironmentMembership) {
                return;
            }

            $idsToDelete = $memberships
                ->reject(fn (ManagedEnvironmentMembership $m): bool => $m->getKey() === $membershipToKeep->getKey())
                ->pluck($membershipToKeep->getKeyName())
                ->all();

            ManagedEnvironmentMembership::query()
                ->whereIn($membershipToKeep->getKeyName(), $idsToDelete)
                ->delete();

            $this->auditLogger->log(
                tenant: $tenant,
                action: AuditActionId::TenantMembershipDuplicatesMerged->value,
                context: [
                    'metadata' => [
                        'member_user_id' => (int) $member->getKey(),
                        'kept_membership_id' => (string) $membershipToKeep->getKey(),
                        'deleted_membership_ids' => array_values(array_map('strval', $idsToDelete)),
                    ],
                ],
                actorId: (int) $actor->getKey(),
                actorEmail: $actor->email,
                actorName: $actor->name,
                status: 'success',
                resourceType: 'tenant',
                resourceId: (string) $tenant->getKey(),
            );
        });
    }

}
