<?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\RefreshDatabase;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Support\Facades\Config;
use Mockery\MockInterface;
use Mtc\MercuryDataModels\Tenant;
use Spatie\Permission\Middlewares\PermissionMiddleware;
use Spatie\Permission\Middlewares\RoleMiddleware;
use Stancl\Tenancy\Middleware\InitializeTenancyByRequestData;

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

    protected function setUp(): void
    {
        parent::setUp();
        $fakeTenant = new Tenant([
            'tier' => Tier::ENTERPRISE->value,
        ]);
        $fakeTenant->id = 'test-tenant';

        $this->withoutMiddleware([
            'auth:sanctum',
            InitializeTenancyByRequestData::class,
            InitializeTenancyByDomain::class,
            TrackRequests::class,
            PermissionMiddleware::class,
            RoleMiddleware::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 migrateUsing()
    {
        return [
            '--schema-path' => database_path('schema/test-tenant-schema.sql'),
            '--path' => database_path('migrations/tenant'),
            '--realpath' => true,
        ];
    }
}
