<?php

declare(strict_types=1);

use classes\email;
use objects\users_o;

putenv('EMAIL_FAKE_MODE=1');

usesApiSuite();

beforeEach(function (): void {
    email::resetFakeDeliveries();
});

it('persists superuser new customer notification preferences and includes them in session payloads', function (): void {
    api_test_covers('PUT /account/notifications', 'happy');

    $session = api_fixtures()->createUserSession([
        'user_notifications_update',
        'superuser',
    ]);

    $response = api_client()->put('/account/notifications', [
        users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS => true,
    ], $session['headers']);

    $response
        ->assertStatus(200)
        ->assertEnvelope()
        ->assertSuccess();

    $key = api_test_runtime()->db()->real_escape_string(users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS);
    $storedPreference = api_test_runtime()->queryOne(
        "SELECT val FROM user_key_value_pairs WHERE user_id = " . (int)$session['user']['id'] . " AND var = '$key'"
    );

    expect($storedPreference)
        ->toBeArray()
        ->toHaveKey('val', '1');

    $sessionResponse = api_client()->get('/auth/session', $session['headers']);

    $sessionResponse
        ->assertStatus(200)
        ->assertEnvelope()
        ->assertSuccess();

    expect($sessionResponse->data()['notifications'][users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS] ?? null)
        ->toBeTrue();
});

it('invalidates cached session payloads after notification preferences change', function (): void {
    api_test_covers('PUT /account/notifications', 'cache');

    $permissions = [
        'fetch_session',
        'user_notifications_update',
        'superuser',
    ];
    $session = api_fixtures()->createUserSession($permissions);
    api_fixtures()->cacheAuthSessionForUser($session['user'], $session['token'], $permissions, [
        'notifications' => [
            users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS => false,
        ],
    ]);

    $cachedSessionResponse = api_client()->get('/auth/session', $session['headers']);

    $cachedSessionResponse
        ->assertStatus(200)
        ->assertEnvelope()
        ->assertSuccess();

    expect($cachedSessionResponse->data()['notifications'][users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS] ?? null)
        ->toBeFalse();

    $response = api_client()->put('/account/notifications', [
        users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS => true,
    ], $session['headers']);

    $response
        ->assertStatus(200)
        ->assertEnvelope()
        ->assertSuccess();

    $sessionResponse = api_client()->get('/auth/session', $session['headers']);

    $sessionResponse
        ->assertStatus(200)
        ->assertEnvelope()
        ->assertSuccess();

    expect($sessionResponse->data()['notifications'][users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS] ?? null)
        ->toBeTrue();
});

it('requires superuser permission before saving superuser new customer notification preferences', function (): void {
    api_test_covers('PUT /account/notifications', 'auth');

    $session = api_fixtures()->createUserSession([
        'user_notifications_update',
    ]);

    $response = api_client()->put('/account/notifications', [
        users_o::KEY_SUPERUSER_NEW_CUSTOMER_EMAIL_NOTIFICATIONS => true,
    ], $session['headers']);

    $response
        ->assertStatus(403)
        ->assertEnvelope()
        ->assertSuccess(false)
        ->assertMissingPermissions(['superuser']);
});

it('sends new customer registration notifications only to opted-in superusers', function (): void {
    api_test_covers('POST /auth/register/cvr', 'notification');

    api_fixtures()->setModuleConfig('Email', 'mailersend_enabled', 'true', 'bool');

    $customer = api_fixtures()->createUser([
        'display_name' => 'Newly Registered Customer',
    ]);
    $enabledSuperuser = api_fixtures()->createUser([
        'display_name' => 'Enabled Superuser',
        'email' => 'enabled-superuser@example.test',
    ], ['superuser']);
    $regularUser = api_fixtures()->createUser([
        'display_name' => 'Enabled Regular User',
        'email' => 'enabled-regular@example.test',
    ]);
    $disabledSuperuser = api_fixtures()->createUser([
        'display_name' => 'Disabled Superuser',
        'email' => 'disabled-superuser@example.test',
    ], ['superuser']);

    (new users_o())
        ->select((int)$enabledSuperuser['id'])
        ->setSuperuserNewCustomerEmailNotificationsEnabled(true);
    (new users_o())
        ->select((int)$regularUser['id'])
        ->setSuperuserNewCustomerEmailNotificationsEnabled(true);
    (new users_o())
        ->select((int)$disabledSuperuser['id'])
        ->setSuperuserNewCustomerEmailNotificationsEnabled(false);

    (new email())->sendNewCustomerRegistrationNotifications((int)$customer['customer_number']);

    expect(email::$fake_deliveries)
        ->toHaveCount(1)
        ->and(email::$fake_deliveries[0]['to'] ?? null)
        ->toBe('enabled-superuser@example.test')
        ->and(email::$fake_deliveries[0]['subject'] ?? null)
        ->toBe('New customer registered on Truck Wash')
        ->and(email::$fake_deliveries[0]['html'] ?? '')
        ->toContain((string)$customer['customer_number']);
});
