<?php

use App\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('marks tenant app status ok on successful admin consent ping', function () {
    $tenant = Tenant::create([
        'tenant_id' => 'tenant-1',
        'name' => 'Contoso',
    ]);

    $response = $this->get(route('admin.consent.callback', [
        'tenant' => $tenant->tenant_id,
        'admin_consent' => 'true',
    ]));

    $response->assertOk();

    $tenant->refresh();
    expect($tenant->app_status)->toBe('ok');

    $this->assertDatabaseHas('audit_logs', [
        'tenant_id' => $tenant->id,
        'action' => 'tenant.consent.callback',
        'status' => 'success',
    ]);
});

it('creates tenant if not existing and marks pending when onboarded without consent flag', function () {
    $response = $this->get(route('admin.consent.callback', [
        'tenant' => 'new-tenant',
        'state' => 'state-456',
    ]));

    $response->assertOk();

    $tenant = Tenant::where('tenant_id', 'new-tenant')->first();
    expect($tenant)->not->toBeNull();
    expect($tenant->app_status)->toBe('pending');
});

it('records error when consent callback includes error query', function () {
    $tenant = Tenant::create([
        'tenant_id' => 'tenant-2',
        'name' => 'Fabrikam',
    ]);

    $response = $this->get(route('admin.consent.callback', [
        'tenant' => $tenant->tenant_id,
        'error' => 'access_denied',
    ]));

    $response->assertOk();

    $tenant->refresh();
    expect($tenant->app_status)->toBe('error');
    expect($tenant->app_notes)->toBe('access_denied');

    $this->assertDatabaseHas('audit_logs', [
        'tenant_id' => $tenant->id,
        'action' => 'tenant.consent.callback',
        'status' => 'error',
    ]);
});
