<?php

namespace Tests;

use App\Tier;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Support\Facades\Event;
use Mtc\MercuryDataModels\Tenant;
use Stancl\Tenancy\Events\TenantCreated;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;
    use DispatchesJobs;

    protected $tenancy = false;
    protected bool $tenancy_make_databases = true;

    protected function setUp(): void
    {
        parent::setUp();

        // Fake further events for tenant created to avoid building database for tenants
        if (!$this->tenancy_make_databases) {
            Event::fake([TenantCreated::class]);
        }

        if ($this->tenancy) {
            $this->initializeTenancy();
        }
    }

    public function initializeTenancy()
    {
        $tenant = Tenant::create([
            'tier' => Tier::LITE->value,
        ]);
        $tenant->domains()->create([
            'domain' => 'test.localhost',
            'verified' => true,
            'primary' => true,
        ]);
        tenancy()->initialize($tenant);
    }

    protected function tearDown(): void
    {
        if (in_array(RefreshDatabase::class, class_uses(static::class))) {
            Tenant::all()->each(fn($tenant) => $tenant->delete());
        }
        parent::tearDown();

        gc_collect_cycles();
    }
}
