<?php

declare(strict_types=1);

use App\Models\Project;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;

/**
 * Smoke-тесты Eloquent-моделей tenant-уровня (Tenant, User, Project).
 * Проверяют factories, связи и базовые операции CRUD под superuser
 * (без RLS — это отдельно в RlsSmokeTest).
 */
uses(DatabaseTransactions::class);

test('TenantFactory создаёт тенанта с уникальным subdomain', function () {
    $tenant = Tenant::factory()->create();

    expect($tenant->id)->toBeInt();
    expect($tenant->subdomain)->toStartWith('tenant-');
    expect($tenant->is_trial)->toBeTrue();
    expect($tenant->api_key_limit)->toBe(5);
});

test('UserFactory создаёт пользователя в тенанте через factory()', function () {
    $user = User::factory()->create();

    expect($user->tenant_id)->toBeInt();
    expect($user->email)->toContain('@');
    expect($user->password_hash)->not->toBeEmpty();
    expect($user->is_active)->toBeTrue();
});

test('ProjectFactory создаёт проект с дефолтным regions/days mask', function () {
    $project = Project::factory()->create();

    expect($project->tenant_id)->toBeInt();
    expect($project->type)->toBe('webhook');
    expect($project->region_mask)->toBe(255);
    expect($project->delivery_days_mask)->toBe(127);
    expect($project->assignment_strategy)->toBe('manual');
});

test('Tenant->users() возвращает связанных пользователей', function () {
    $tenant = Tenant::factory()->create();
    User::factory()->count(3)->create(['tenant_id' => $tenant->id]);

    expect($tenant->users)->toHaveCount(3);
    expect($tenant->users->first())->toBeInstanceOf(User::class);
});

test('Tenant->projects() возвращает связанные проекты', function () {
    $tenant = Tenant::factory()->create();
    Project::factory()->count(2)->create(['tenant_id' => $tenant->id]);

    expect($tenant->projects)->toHaveCount(2);
});

test('User->tenant() возвращает родителя', function () {
    $tenant = Tenant::factory()->create();
    $user = User::factory()->create(['tenant_id' => $tenant->id]);

    expect($user->tenant->id)->toBe($tenant->id);
});

test('Project->tenant() возвращает родителя', function () {
    $tenant = Tenant::factory()->create();
    $project = Project::factory()->create(['tenant_id' => $tenant->id]);

    expect($project->tenant->id)->toBe($tenant->id);
});

test('User используется password_hash вместо password (override)', function () {
    $user = User::factory()->create();

    expect($user->getAuthPassword())->toBe($user->password_hash);
    expect($user->getAuthPasswordName())->toBe('password_hash');
});
