<?php

namespace Tests\Feature\Http\Controllers\Api\V1;

use App\Models\PlatformAccount;
use App\Models\PlatformInstance;
use App\Services\Auth\LemmyAuthService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Mockery;
use Tests\TestCase;

class PlatformAccountsControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_index_returns_successful_response(): void
    {
        $instance = PlatformInstance::factory()->create();
        PlatformAccount::factory()->count(3)->create();

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

        $response->assertStatus(200)
            ->assertJsonStructure([
                'success',
                'message',
                'data' => [
                    '*' => [
                        'id',
                        'platform',
                        'instance_url',
                        'username',
                        'is_active',
                        'created_at',
                        'updated_at',
                    ],
                ],
            ])
            ->assertJson([
                'success' => true,
                'message' => 'Platform accounts retrieved successfully.',
            ]);
    }

    public function test_store_creates_platform_account_successfully(): void
    {
        $mockAuth = Mockery::mock(LemmyAuthService::class);
        $mockAuth->shouldReceive('authenticate')
            ->once()
            ->with('https://lemmy.example.com', 'testuser', 'testpass123')
            ->andReturn([
                'jwt' => 'test-token',
                'person_view' => ['person' => ['id' => 1, 'display_name' => null, 'bio' => null]],
            ]);
        $this->app->instance(LemmyAuthService::class, $mockAuth);

        $data = [
            'platform' => 'lemmy',
            'instance_domain' => 'lemmy.example.com',
            'username' => 'testuser',
            'password' => 'testpass123',
        ];

        $response = $this->postJson('/api/v1/platform-accounts', $data);

        $response->assertStatus(201)
            ->assertJsonStructure([
                'success',
                'message',
                'data' => [
                    'id',
                    'platform',
                    'instance_url',
                    'username',
                    'is_active',
                    'created_at',
                    'updated_at',
                ],
            ])
            ->assertJson([
                'success' => true,
                'message' => 'Platform account created successfully!',
            ]);

        $this->assertDatabaseHas('platform_accounts', [
            'platform' => 'lemmy',
            'instance_url' => 'https://lemmy.example.com',
            'username' => 'testuser',
        ]);
    }

    public function test_store_validates_required_fields(): void
    {
        $response = $this->postJson('/api/v1/platform-accounts', []);

        $response->assertStatus(422)
            ->assertJsonValidationErrors(['platform', 'instance_domain', 'username', 'password']);
    }

    public function test_show_returns_platform_account_successfully(): void
    {
        $account = PlatformAccount::factory()->create();

        $response = $this->getJson("/api/v1/platform-accounts/{$account->id}");

        $response->assertStatus(200)
            ->assertJsonStructure([
                'success',
                'message',
                'data' => [
                    'id',
                    'platform',
                    'instance_url',
                    'username',
                    'is_active',
                    'created_at',
                    'updated_at',
                ],
            ])
            ->assertJson([
                'success' => true,
                'message' => 'Platform account retrieved successfully.',
                'data' => [
                    'id' => $account->id,
                    'username' => $account->username,
                ],
            ]);
    }

    public function test_update_modifies_platform_account_successfully(): void
    {
        $account = PlatformAccount::factory()->create();

        $updateData = [
            'instance_url' => 'https://updated.example.com',
            'username' => 'updateduser',
            'settings' => ['updated' => 'value'],
        ];

        $response = $this->putJson("/api/v1/platform-accounts/{$account->id}", $updateData);

        $response->assertStatus(200)
            ->assertJson([
                'success' => true,
                'message' => 'Platform account updated successfully!',
            ]);

        $this->assertDatabaseHas('platform_accounts', [
            'id' => $account->id,
            'instance_url' => 'https://updated.example.com',
            'username' => 'updateduser',
        ]);
    }

    public function test_destroy_deletes_platform_account_successfully(): void
    {
        $account = PlatformAccount::factory()->create();

        $response = $this->deleteJson("/api/v1/platform-accounts/{$account->id}");

        $response->assertStatus(200)
            ->assertJson([
                'success' => true,
                'message' => 'Platform account deleted successfully!',
            ]);

        $this->assertDatabaseMissing('platform_accounts', [
            'id' => $account->id,
        ]);
    }

    public function test_set_active_activates_platform_account(): void
    {
        $account = PlatformAccount::factory()->create(['is_active' => false]);

        $response = $this->postJson("/api/v1/platform-accounts/{$account->id}/set-active");

        $response->assertStatus(200)
            ->assertJson([
                'success' => true,
            ]);

        $this->assertDatabaseHas('platform_accounts', [
            'id' => $account->id,
            'is_active' => true,
        ]);
    }

    public function test_set_active_deactivates_other_accounts_of_same_platform(): void
    {
        $activeAccount = PlatformAccount::factory()->create([
            'platform' => 'lemmy',
            'is_active' => true,
        ]);

        $newAccount = PlatformAccount::factory()->create([
            'platform' => 'lemmy',
            'is_active' => false,
        ]);

        $response = $this->postJson("/api/v1/platform-accounts/{$newAccount->id}/set-active");

        $response->assertStatus(200);

        $this->assertDatabaseHas('platform_accounts', [
            'id' => $activeAccount->id,
            'is_active' => false,
        ]);

        $this->assertDatabaseHas('platform_accounts', [
            'id' => $newAccount->id,
            'is_active' => true,
        ]);
    }
}
