<?php

declare(strict_types=1);

use App\Mail\SupportRequestMail;
use App\Models\SupportRequest;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Mail;

uses(DatabaseTransactions::class);

use function Pest\Laravel\actingAs;
use function Pest\Laravel\postJson;

beforeEach(function () {
    $this->tenant = Tenant::factory()->create();
    $this->user = User::factory()->create(['tenant_id' => $this->tenant->id]);
});

it('создаёт заявку в БД и ставит письмо в очередь', function () {
    Mail::fake();
    actingAs($this->user);

    postJson('/api/support-requests', [
        'name' => 'Иван',
        'contact' => '+79991234567',
        'message' => 'Не приходят лиды.',
    ])->assertCreated()->assertJson(['ok' => true]);

    $row = SupportRequest::query()->where('tenant_id', $this->tenant->id)->first();
    expect($row)->not->toBeNull()
        ->and($row->user_id)->toBe($this->user->id)
        ->and($row->name)->toBe('Иван')
        ->and($row->contact)->toBe('+79991234567')
        ->and($row->message)->toBe('Не приходят лиды.');

    Mail::assertQueued(SupportRequestMail::class, fn (SupportRequestMail $m) => $m->hasTo(config('services.support.email')));
});

it('валидирует обязательные поля (422)', function () {
    Mail::fake();
    actingAs($this->user);
    postJson('/api/support-requests', ['name' => '', 'contact' => '', 'message' => ''])
        ->assertStatus(422)
        ->assertJsonValidationErrors(['name', 'contact', 'message']);
});

it('не теряет заявку при сбое почты', function () {
    Mail::shouldReceive('to')->andThrow(new RuntimeException('smtp down'));

    actingAs($this->user);

    postJson('/api/support-requests', [
        'name' => 'Пётр', 'contact' => 'p@example.org', 'message' => 'Вопрос.',
    ])->assertCreated();

    expect(SupportRequest::query()->where('tenant_id', $this->tenant->id)->count())->toBe(1);
});
