<?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 Mtc\Notifications\Facades\Notification;
use Stancl\Tenancy\Events\TenantCreated;

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

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

    protected bool $withoutMiddlewares = false;

    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]);
            Notification::shouldReceive('hasUnread')->andReturn(false);
        }

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

        if ($this->withoutMiddlewares) {
            $this->withoutMiddleware();
        }
    }

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