<?php

declare(strict_types=1);

use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Tests\Concerns\SharesSupplierPdo;

// Самозапись и backfill пишут users через BYPASSRLS pgsql_supplier (нет tenant-GUC
// на публичном роуте). SharesSupplierPdo шарит PDO под DatabaseTransactions.
uses(DatabaseTransactions::class, SharesSupplierPdo::class);

beforeEach(function () {
    config(['services.captcha.fake_passes' => true]);
});

test('самозапись даёт new_lead.email=true по DB-дефолту', function () {
    $this->postJson('/api/auth/register', [
        'email' => 'digeston@example.ru',
        'password' => 'fresh-pass-123',
        'accept_offer' => true,
        'accept_pdn' => true,
        'captcha_token' => 'tok-123',
    ])->assertStatus(201);

    $user = User::where('email', 'digeston@example.ru')->first();
    expect(data_get($user->notification_preferences, 'new_lead.email'))->toBeTrue();
});

test('backfill дотягивает new_lead.email false→true, не трогая соседние', function () {
    $user = User::factory()->create([
        'notification_preferences' => [
            'new_lead' => ['inapp' => true, 'push' => true, 'email' => false],
            'reminder' => ['inapp' => true, 'push' => true, 'email' => true],
            'low_balance' => ['email' => true],
        ],
    ]);

    DB::connection('pgsql_supplier')->statement(<<<SQL
        UPDATE users
           SET notification_preferences = jsonb_set(notification_preferences, '{new_lead,email}', 'true'::jsonb)
         WHERE id = {$user->id}
           AND notification_preferences #> '{new_lead,email}' = 'false'::jsonb
        SQL);

    $fresh = User::find($user->id);
    expect(data_get($fresh->notification_preferences, 'new_lead.email'))->toBeTrue();
    expect(data_get($fresh->notification_preferences, 'reminder.email'))->toBeTrue();
});
