<?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 $tenancy_make_databases = false;

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

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

        // Fake further events for tenant created to avoid building database for tenants
        Event::fake([TenantCreated::class]);
    }

    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();
    }
}
