<?php

namespace Tests\Feature\Middleware;

use App\Http\Middleware\EnsureUserBelongsToTenant;
use Database\Seeders\Global\GlobalRoleSeed;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\User;
use Symfony\Component\HttpFoundation\Response;
use Tests\DatabaseTestCase;

class EnsureUserBelongsToTenantTest extends DatabaseTestCase
{
    private EnsureUserBelongsToTenant $middleware;

    #[\Override]
    protected function setUp(): void
    {
        parent::setUp();

        $this->middleware = new EnsureUserBelongsToTenant();
        (new GlobalRoleSeed())->run();
        tenant()->saveQuietly();
    }

    public function testDeniesUserWithoutMembershipForActiveTenant(): void
    {
        // AUTO-1676: a user who only belongs to another tenant must not be able
        // to operate on the active tenant resolved from the X-Tenant header.
        $user = User::factory()->create();
        $user->tenants()->attach('some-other-tenant', ['role' => 'Editor']);

        $response = $this->getResponse($user);

        $this->assertEquals(403, $response->getStatusCode());
        $this->assertStringContainsString('Access Denied', $response->getContent());
    }

    public function testAllowsUserWithMembershipForActiveTenant(): void
    {
        $user = User::factory()->create();
        $user->tenants()->attach(tenant('id'), ['role' => 'Editor']);

        $response = $this->getResponse($user);

        $this->assertEquals(200, $response->getStatusCode());
    }

    public function testAllowsMtcSuperadminWithoutTenantMembership(): void
    {
        // mtc superadmins are not tied to a specific tenant but manage all sites.
        $user = User::factory()->create();
        setPermissionsTeamId(tenant('id'));
        $user->assignRole('mtc');

        $response = $this->getResponse($user);

        $this->assertEquals(200, $response->getStatusCode());
    }

    public function testAllowsUnauthenticatedRequestToPassThrough(): void
    {
        $response = $this->getResponse(null);

        $this->assertEquals(200, $response->getStatusCode());
    }

    private function getResponse(?User $user): Response
    {
        $request = Request::create('/dummy', 'GET');
        $request->setUserResolver(fn () => $user);

        return $this->middleware->handle($request, fn () => response('ok'));
    }
}
