<?php

namespace Tests\Unit\Services\Users;

use App\Services\School\AccountEventService;
use App\Services\Users\DeleteUnverifiedUserService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Mockery;
use Tests\TestCase;

class DeleteUnverifiedUserServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_delete_after_timeout_deletes_user(): void
    {
        DB::table('users')->insert([
            'id' => 10,
            'firstname' => 'Unverified',
            'lastname' => 'User',
            'email' => 'u@example.com',
            'status' => 'Inactive',
            'is_verified' => 0,
            'created_at' => now()->subDays(2),
            'updated_at' => now()->subDays(2),
        ]);

        DB::table('user_roles')->insert([
            'user_id' => 10,
            'role_id' => 1,
        ]);

        $accountEvents = Mockery::mock(AccountEventService::class);
        $accountEvents->shouldReceive('deleteUnverifiedUser')->once();

        $service = new DeleteUnverifiedUserService($accountEvents);
        $result = $service->deleteAfterTimeout(10, 3600);

        $this->assertTrue($result['ok']);
        $this->assertDatabaseMissing('users', ['id' => 10]);
        $this->assertDatabaseMissing('user_roles', ['user_id' => 10]);
    }

    public function test_delete_after_timeout_skips_recent_user(): void
    {
        DB::table('users')->insert([
            'id' => 11,
            'firstname' => 'Recent',
            'lastname' => 'User',
            'email' => 'recent@example.com',
            'status' => 'Inactive',
            'is_verified' => 0,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $accountEvents = Mockery::mock(AccountEventService::class);
        $accountEvents->shouldNotReceive('deleteUnverifiedUser');

        $service = new DeleteUnverifiedUserService($accountEvents);
        $result = $service->deleteAfterTimeout(11, 86400);

        $this->assertFalse($result['ok']);
        $this->assertSame('not_expired', $result['reason']);
        $this->assertDatabaseHas('users', ['id' => 11]);
    }
}
