<?php

namespace Tests\Feature;

use App\Models\Central\Company;
use App\Models\Central\Plan;
use App\Models\Tenant\User;
use App\Tenancy\TenantManager;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;

/**
 * User-ul tenant A NU trebuie să poată se logheze pe subdomain-ul tenant B.
 * Garanție 1-user-1-tenant.
 */
class AuthFlowTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_cannot_login_on_wrong_subdomain(): void
    {
        $plan = Plan::create([
            'name' => 'Test', 'slug' => 'test', 'price' => 0, 'features' => [],
        ]);
        $companyA = Company::create([
            'plan_id' => $plan->id,
            'slug' => 'company-a-' . uniqid(),
            'name' => 'A', 'status' => 'active',
        ]);
        $companyB = Company::create([
            'plan_id' => $plan->id,
            'slug' => 'company-b-' . uniqid(),
            'name' => 'B', 'status' => 'active',
        ]);

        app(TenantManager::class)->setCurrent($companyA);
        $userA = User::create([
            'company_id' => $companyA->id,
            'name' => 'Alice',
            'email' => 'alice@a.com',
            'password' => Hash::make('secret123'),
            'status' => 'active',
        ]);

        // Switch to company B context — try to attempt() with A's credentials
        app(TenantManager::class)->setCurrent($companyB);
        $ok = auth('web')->attempt(['email' => 'alice@a.com', 'password' => 'secret123']);

        $this->assertFalse($ok, 'User from company A authenticated successfully on company B subdomain');
    }

    public function test_user_can_login_on_own_subdomain(): void
    {
        $plan = Plan::create([
            'name' => 'Test', 'slug' => 'test', 'price' => 0, 'features' => [],
        ]);
        $company = Company::create([
            'plan_id' => $plan->id,
            'slug' => 'mine-' . uniqid(),
            'name' => 'Mine', 'status' => 'active',
        ]);

        app(TenantManager::class)->setCurrent($company);
        User::create([
            'company_id' => $company->id,
            'name' => 'Bob',
            'email' => 'bob@mine.com',
            'password' => Hash::make('pwd12345'),
            'status' => 'active',
        ]);

        $ok = auth('web')->attempt(['email' => 'bob@mine.com', 'password' => 'pwd12345']);

        $this->assertTrue($ok);
    }
}
