<?php

namespace Tests;

use App\Newsletter\CampaignMonitor;
use App\Newsletter\MailChimp;
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();

        $this->app->bind(MailChimp::class, function () {
            return new MailChimp(new FakeMailchimp('test-api-key'));
        });

        $this->app->bind(CampaignMonitor::class, function () {
            return new CampaignMonitor(new FakeCampaignMonitor('list-id', ['api_key' => 'test-api-key']));
        });

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

        $this->withoutExceptionHandling();

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

    public function initializeTenancy()
    {
        /** @var Tenant $tenant */
        $tenant = Tenant::create([
            'tier' => 'pro',
        ]);
        $tenant->domains()->create(['domain' => 'demo.com']);
        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();
    }


    protected function asTenant($tenant)
    {
        $this->withHeader('X-Tenant', 'demo.com');
        return $this;
    }
}
