<?php

namespace App\Services\Users;

use App\Models\User;
use App\Services\School\AccountEventService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class DeleteUnverifiedUserService
{
    public function __construct(private AccountEventService $accountEvents)
    {
    }

    public function deleteAfterTimeout(int $userId, int $timeoutSeconds = 86400): array
    {
        $user = User::query()->find($userId);
        if (!$user) {
            return ['ok' => false, 'reason' => 'not_found'];
        }

        if ((int) ($user->is_verified ?? 0) === 1) {
            return ['ok' => false, 'reason' => 'verified'];
        }

        $lastActivity = $user->updated_at ?? $user->created_at;
        if (!$lastActivity) {
            return ['ok' => false, 'reason' => 'no_timestamp'];
        }

        $cutoff = now()->subSeconds($timeoutSeconds);
        if ($lastActivity > $cutoff) {
            return ['ok' => false, 'reason' => 'not_expired'];
        }

        $userPayload = $user->toArray();

        DB::transaction(function () use ($userId, $user): void {
            DB::table('user_roles')->where('user_id', $userId)->delete();
            $user->delete();
        });

        $this->accountEvents->deleteUnverifiedUser($userPayload);

        Log::info('Deleted unverified user after timeout.', ['user_id' => $userId]);

        return ['ok' => true, 'deleted' => true, 'user_id' => $userId];
    }
}
