<?php

use Modules\Shared\Support\EnvFileWriter;

beforeEach(function () {
    $this->path = sys_get_temp_dir().'/env-file-writer-test-'.uniqid().'.env';
});

afterEach(function () {
    @unlink($this->path);
});

test('it replaces an existing key in place without touching other lines', function () {
    file_put_contents($this->path, "APP_NAME=Laravel\nAPP_ENV=local\n");

    (new EnvFileWriter($this->path))->write(['APP_NAME' => 'New Name']);

    expect(file_get_contents($this->path))->toBe("APP_NAME=\"New Name\"\nAPP_ENV=local\n");
});

test('it appends a missing key at the end of the file', function () {
    file_put_contents($this->path, "APP_NAME=Laravel\n");

    (new EnvFileWriter($this->path))->write(['SUPPORT_EMAIL' => 'support@example.com']);

    expect(file_get_contents($this->path))->toBe("APP_NAME=Laravel\nSUPPORT_EMAIL=support@example.com\n");
});

test('it formats booleans as bare true/false', function () {
    file_put_contents($this->path, '');

    (new EnvFileWriter($this->path))->write(['BOOKING_BACK_SEAT_ENABLED' => false]);

    expect(file_get_contents($this->path))->toContain('BOOKING_BACK_SEAT_ENABLED=false');
});

test('it quotes values containing whitespace', function () {
    file_put_contents($this->path, '');

    (new EnvFileWriter($this->path))->write(['APP_NAME' => 'My Company']);

    expect(file_get_contents($this->path))->toContain('APP_NAME="My Company"');
});

test('it writes multiple keys in one call', function () {
    file_put_contents($this->path, "APP_NAME=Laravel\n");

    (new EnvFileWriter($this->path))->write([
        'APP_NAME' => 'Renamed',
        'APP_CURRENCY' => 'MMK',
        'BOOKING_FRONT_SEAT_MAX_PER_BOOKING' => 2,
    ]);

    $contents = file_get_contents($this->path);

    expect($contents)
        ->toContain('APP_NAME=Renamed')
        ->toContain('APP_CURRENCY=MMK')
        ->toContain('BOOKING_FRONT_SEAT_MAX_PER_BOOKING=2');
});
