<?php

namespace Tests\Feature;

use App\Models\User;
use Tests\TestCase;

/**
 * Renders the staff-facing screens this programme added, against a restored
 * copy of a real tenant database.
 *
 *   DB_CONNECTION=pgsql DB_DATABASE=oc_sport_test ./vendor/bin/phpunit --filter AdminScreensSmokeTest
 */
class AdminScreensSmokeTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        if (config('database.default') !== 'pgsql') {
            $this->markTestSkipped('Needs a restored Postgres tenant.');
        }
    }

    public function test_the_new_staff_screens_render_for_an_owner(): void
    {
        $owner = User::withoutGlobalScopes()
            ->whereHas('primaryRole', fn ($q) => $q->where('slug', 'academy_owner'))
            ->firstOrFail();

        foreach ([
            'payment-proofs.index',
            'portal-invitations.index',
            'users.duplicates',
            'attendance.scan',
            'service-requests.index',
            'reports.transfer-reconciliation',
            'participants.pending',
        ] as $name) {
            $response = $this->actingAs($owner)->get(route($name));

            fwrite(STDERR, sprintf("  %-26s %d  %6d bytes\n",
                $name, $response->getStatusCode(), strlen($response->getContent())));

            if ($response->getStatusCode() !== 200) {
                fwrite(STDERR, '     ' . substr(strip_tags($response->getContent()), 0, 300) . "\n");
            }

            $this->assertSame(200, $response->getStatusCode(), "{$name} did not render");
        }
    }

    public function test_a_member_account_cannot_reach_a_staff_screen(): void
    {
        $resolver = app(\App\Domain\Identity\Services\GuardianResolver::class);

        $member = User::withoutGlobalScopes()->whereNotNull('person_id')->limit(200)->get()
            ->first(fn ($u) => $resolver->participantIdsFor($u) !== [] && ! $u->can('payments.approve_proof'));

        if (! $member) {
            $this->markTestSkipped('No member account without the approval permission on this tenant.');
        }

        $this->actingAs($member)->get(route('payment-proofs.index'))->assertForbidden();
        $this->actingAs($member)->get(route('attendance.scan'))->assertForbidden();
    }
}
