<?php

namespace Tests\Feature;

use App\Models\Central\Company;
use App\Models\Central\Plan;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class OffsiteBackupTest extends TestCase
{
    use RefreshDatabase;

    public function test_backup_uploads_to_b2_when_configured(): void
    {
        $plan = Plan::create(['name' => 'F', 'slug' => 'free', 'price' => 0, 'features' => []]);
        Company::create([
            'plan_id' => $plan->id, 'slug' => 'bkup',
            'name' => 'Backup Co', 'status' => 'active',
        ]);

        // Pretend B2 is configured + fake the disk so the command's putStream lands here.
        putenv('B2_KEY=fake');
        putenv('B2_BUCKET=fake-bucket');
        $b2 = Storage::fake('b2');

        $this->artisan('backup:tenants --slug=bkup')->assertExitCode(0);

        // The remote key uses today's date + slug.
        $remoteKey = date('Y-m-d') . '/bkup.zip';
        $b2->assertExists($remoteKey);

        putenv('B2_KEY');
        putenv('B2_BUCKET');
    }

    public function test_backup_skips_offsite_when_not_configured(): void
    {
        $plan = Plan::firstOrCreate(['slug' => 'free'], ['name' => 'F', 'price' => 0, 'features' => []]);
        Company::create([
            'plan_id' => $plan->id, 'slug' => 'nob2',
            'name' => 'No B2', 'status' => 'active',
        ]);

        // No B2 env set.
        $b2 = Storage::fake('b2');

        $this->artisan('backup:tenants --slug=nob2')->assertExitCode(0);

        // Nothing pushed offsite.
        $this->assertCount(0, $b2->allFiles());
    }
}
