<?php

namespace Tests\Tenant\Controllers;

use App\Facades\Settings;
use App\Models\ExportMap;
use App\Models\ExportMapTemplate;
use Illuminate\Support\Facades\Event;
use Tests\DatabaseTestCase;
use Tests\UserForTenant;

/**
 * Covers AUTO-1603: export maps in the sales channels list and the
 * supports_auto_trader flag. Uses the master DB so ExportMapTemplate (central
 * connection) is available.
 */
class SalesChannelExportMapTest extends DatabaseTestCase
{
    use UserForTenant;

    protected bool $useTestSettingRepository = false;

    private function enableChannel(string $channel): void
    {
        Settings::make([
            'tab' => 'Automotive',
            'section' => 'Sales Channels / Feeds',
            'group' => $channel,
            'name' => 'Enabled',
            'type' => 'boolean',
            'value' => true,
            'config_key' => 'sales-channels-' . $channel . '-enabled',
        ]);
    }

    private function indexTitles(): \Illuminate\Support\Collection
    {
        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->getJson(route('tenant.sales-channels.index'));

        $response->assertStatus(200);

        return collect($response->json('data'));
    }

    public function testIndexHidesChannelWithActiveExportMapAndListsTheExportMap(): void
    {
        Event::fake();
        $this->enableChannel('car-gurus');
        $this->enableChannel('car-wow');

        $template = ExportMapTemplate::factory()->create([
            'sales_channel' => 'car-gurus',
            'is_published' => true,
            'type' => 'vehicle',
        ]);
        $map = ExportMap::factory()->create([
            'slug' => 'car-gurus-map',
            'name' => 'Car Gurus Export Map',
            'template_id' => $template->id,
            'active' => true,
            'ftp_export_enabled' => true,
        ]);

        $data = $this->indexTitles();
        $titles = $data->pluck('title');

        // Integration tile hidden; export map listed in its place.
        $this->assertFalse($titles->contains('CarGuru'));
        $this->assertTrue($titles->contains('Car Gurus Export Map'));
        // Channel without an active export map is unaffected.
        $this->assertTrue($titles->contains('CarWow'));

        $entry = $data->firstWhere('title', 'Car Gurus Export Map');
        $this->assertTrue($entry['active']);
        $this->assertEquals('/settings/export-maps/edit/' . $map->id, $entry['link']);
    }

    public function testIndexKeepsIntegrationWhenExportMapInactive(): void
    {
        Event::fake();
        $this->enableChannel('car-gurus');

        $template = ExportMapTemplate::factory()->create([
            'sales_channel' => 'car-gurus',
            'is_published' => true,
            'type' => 'vehicle',
        ]);
        ExportMap::factory()->create([
            'slug' => 'inactive-map',
            'name' => 'Inactive Map',
            'template_id' => $template->id,
            'active' => false,
            'ftp_export_enabled' => true,
        ]);

        $data = $this->indexTitles();
        $titles = $data->pluck('title');

        // Inactive export map does not supersede the integration; both listed.
        $this->assertTrue($titles->contains('CarGuru'));
        $this->assertTrue($titles->contains('Inactive Map'));
        $this->assertFalse($data->firstWhere('title', 'Inactive Map')['active']);
    }

    public function testIndexListsEveryExportMapForTheSameChannel(): void
    {
        Event::fake();
        $this->enableChannel('car-gurus');

        $template = ExportMapTemplate::factory()->create([
            'sales_channel' => 'car-gurus',
            'is_published' => true,
            'type' => 'vehicle',
        ]);
        ExportMap::factory()->create([
            'slug' => 'cg-map-one',
            'name' => 'Car Gurus Map One',
            'template_id' => $template->id,
            'active' => true,
            'ftp_export_enabled' => true,
        ]);
        ExportMap::factory()->create([
            'slug' => 'cg-map-two',
            'name' => 'Car Gurus Map Two',
            'template_id' => $template->id,
            'active' => false,
            'ftp_export_enabled' => true,
        ]);

        $titles = $this->indexTitles()->pluck('title');

        // Both export maps for the channel are listed individually.
        $this->assertTrue($titles->contains('Car Gurus Map One'));
        $this->assertTrue($titles->contains('Car Gurus Map Two'));
        // The integration is hidden because an active export map supersedes it.
        $this->assertFalse($titles->contains('CarGuru'));
    }

    public function testIndexExcludesExportMapWithoutAutomatedFtpExport(): void
    {
        Event::fake();
        $this->enableChannel('car-gurus');

        $template = ExportMapTemplate::factory()->create([
            'sales_channel' => 'car-gurus',
            'is_published' => true,
            'type' => 'vehicle',
        ]);
        // "Automated export to FTP server" is off -> not a sales-channel feed.
        ExportMap::factory()->create([
            'slug' => 'manual-map',
            'name' => 'Manual Only Map',
            'template_id' => $template->id,
            'active' => true,
            'ftp_export_enabled' => false,
        ]);

        $titles = $this->indexTitles()->pluck('title');

        // The map is not listed, and the integration is still shown.
        $this->assertFalse($titles->contains('Manual Only Map'));
        $this->assertTrue($titles->contains('CarGuru'));
    }

    public function testShowReturnsSupportsAutoTraderFlag(): void
    {
        Event::fake();
        $this->enableChannel('car-gurus');
        // AutoTrader uses a non-standard enabled key.
        Settings::make([
            'tab' => 'Automotive',
            'section' => 'Sales Channels / Feeds',
            'group' => 'AutoTrader',
            'name' => 'Enabled',
            'type' => 'boolean',
            'value' => true,
            'config_key' => 'sales-channels-auto-trader-enabled',
        ]);

        $carGuru = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->getJson(route('tenant.sales-channels.show', 'car-gurus'));
        $carGuru->assertStatus(200);
        $this->assertFalse($carGuru->json('supports_auto_trader'));

        $autoTrader = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->getJson(route('tenant.sales-channels.show', 'auto-trader-sales'));
        $autoTrader->assertStatus(200);
        $this->assertTrue($autoTrader->json('supports_auto_trader'));
    }
}
