<?php

namespace Tests\Feature\Api\V1\Users;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class UserControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_list_returns_users_with_roles(): void
    {
        $admin = $this->seedUser(1, 'admin@example.com');
        Sanctum::actingAs($admin);

        DB::table('roles')->insert([
            'id' => 10,
            'name' => 'Teacher',
            'slug' => 'teacher',
            'description' => 'Teacher role',
            'dashboard_route' => 'teacher/dashboard',
            'priority' => 1,
            'is_active' => 1,
        ]);

        $this->seedUser(2, 'member@example.com');
        DB::table('user_roles')->insert([
            'user_id' => 2,
            'role_id' => 10,
        ]);

        $response = $this->getJson('/api/v1/users');

        $response->assertOk();
        $response->assertJson(['ok' => true]);
        $response->assertJsonFragment(['email' => 'member@example.com']);
        $response->assertJsonFragment(['roles' => ['Teacher']]);
    }

    public function test_create_user_creates_user_and_role(): void
    {
        $admin = $this->seedUser(1, 'admin@example.com');
        Sanctum::actingAs($admin);

        DB::table('roles')->insert([
            'id' => 20,
            'name' => 'Parent',
            'slug' => 'parent',
            'description' => 'Parent role',
            'dashboard_route' => 'parent/dashboard',
            'priority' => 2,
            'is_active' => 1,
        ]);

        $response = $this->postJson('/api/v1/users', [
            'firstname' => 'New',
            'lastname' => 'User',
            'cellphone' => '5554443333',
            'email' => 'new.user@example.com',
            'address_street' => '123 Main St',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => true,
            'role_id' => 20,
            'password' => 'secret123',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        $response->assertStatus(201);
        $response->assertJson(['ok' => true]);

        $userId = (int) ($response->json('user_id') ?? 0);
        $this->assertGreaterThan(0, $userId);

        $this->assertDatabaseHas('users', [
            'id' => $userId,
            'email' => 'new.user@example.com',
        ]);

        $this->assertDatabaseHas('user_roles', [
            'user_id' => $userId,
            'role_id' => 20,
        ]);
    }

    public function test_login_activity_returns_paginated_results(): void
    {
        $admin = $this->seedUser(1, 'admin@example.com');
        Sanctum::actingAs($admin);

        DB::table('login_activity')->insert([
            'user_id' => 1,
            'email' => 'admin@example.com',
            'login_time' => '2025-01-02 09:00:00',
            'logout_time' => null,
            'ip_address' => '10.0.0.1',
            'user_agent' => 'TestAgent',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        DB::table('login_activity')->insert([
            'user_id' => 1,
            'email' => 'admin@example.com',
            'login_time' => '2025-01-01 09:00:00',
            'logout_time' => null,
            'ip_address' => '10.0.0.2',
            'user_agent' => 'TestAgent',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        $response = $this->json('GET', '/api/v1/users/login-activity', [
            'per_page' => 1,
            'page' => 2,
        ]);

        $response->assertOk();
        $response->assertJson(['ok' => true]);
        $response->assertJsonPath('pagination.total', 2);
        $response->assertJsonPath('pagination.currentPage', 2);
        $response->assertJsonPath('activities.0.ip_address', '10.0.0.2');
    }

    private function seedUser(int $id, string $email): User
    {
        DB::table('users')->insert([
            'id' => $id,
            'school_id' => 1,
            'firstname' => 'Test',
            'lastname' => 'User',
            'cellphone' => '5555555555',
            'email' => $email,
            'address_street' => '123 Main',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'is_verified' => 1,
            'status' => 'Active',
            'is_suspended' => 0,
            'failed_attempts' => 0,
            'password' => bcrypt('secret'),
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        return User::query()->findOrFail($id);
    }
}
