<?php

namespace Tests;

use App\Http\Middleware\TrackRequests;
use App\LocalisationService;
use App\Middleware\InitializeTenancyByDomain;
use App\Newsletter\CampaignMonitor;
use App\Newsletter\MailChimp;
use App\SiteRepository;
use App\Tier;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Support\Facades\Config;
use Mockery\MockInterface;
use Mtc\MercuryDataModels\Tenant;
use Stancl\Tenancy\Middleware\InitializeTenancyByRequestData;

abstract class TenantTestCase extends BaseTestCase
{
    use CreatesApplication;
    use DatabaseMigrations;
    use DispatchesJobs;

    #[\Override]
    protected function setUp(): void
    {
        if (!defined('LARAVEL_START')) {
            define('LARAVEL_START', microtime(true));
        }
        parent::setUp();
        $fakeTenant = new Tenant([
            'tier' => Tier::ENTERPRISE->value,
        ]);
        $fakeTenant->id = 'test-tenant';

        $this->withoutMiddleware([
            'auth:sanctum',
            InitializeTenancyByRequestData::class,
            InitializeTenancyByDomain::class,
            TrackRequests::class,
        ]);

        \tenancy()->initialize($fakeTenant);
        Config::set('database.default', 'sqlite');

        $this->partialMock(SiteRepository::class, function (MockInterface $mock) {
            $mock->shouldReceive('baseUrl')->andReturn('/foo.localhost');
            $mock->shouldReceive('siteDomain')->andReturn('foo.localhost');
        });

        $this->partialMock(LocalisationService::class, function (MockInterface $mock) {
            $mock->shouldReceive('phonePrefix')->andReturn('+44');
        });

        $this->app->bind('feature-flags', TestFeatureRepository::class);
        $this->app->bind('site-settings', TestSettingRepository::class);

        $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']));
        });
    }
    protected function runDatabaseMigrations()
    {
        $this->artisan('migrate:fresh', [
            '--schema-path' => database_path('schema/test-tenant-schema.sql'),
            '--path' => database_path('migrations/tenant'),
            '--realpath' => true,
        ]);
    }
}
