<?php

namespace Tests\Feature\Controllers;

use App\Models\LeadExport;
use App\Models\LeadExportTemplate;
use Tests\DatabaseTestCase;
use Tests\UserForTenant;

class LeadExportControllerTest extends DatabaseTestCase
{
    use UserForTenant;

    protected function setUp(): void
    {
        parent::setUp();
        $this->withHeader('X-Tenant', tenant('id'));
    }

    public function testStoreCreatesExport(): void
    {
        $response = $this->actingAs($this->getUser())
            ->postJson('api/settings/lead-exports', ['name' => 'Partner CRM', 'type' => 'lead']);

        $response->assertStatus(201);
        $this->assertSame('lead', $response->json('type'));
        $this->assertSame('partner-crm', $response->json('slug'));
        $this->assertSame(LeadExport::MODE_MAPPED, $response->json('mode'));
    }

    public function testStoreFromTemplateCopiesStructure(): void
    {
        $template = LeadExportTemplate::query()->create([
            'title' => 'Seed',
            'type' => 'lead',
            'is_published' => true,
            'mode' => LeadExport::MODE_MAPPED,
            'field_map' => [['destination' => 'email', 'label' => 'Email', 'type' => 'string']],
            'config' => [],
        ]);

        $response = $this->actingAs($this->getUser())
            ->postJson('api/settings/lead-exports', [
                'name' => 'From Template',
                'template_id' => $template->id,
            ]);

        $response->assertStatus(201);
        $this->assertSame($template->id, $response->json('template_id'));
        $this->assertSame($template->field_map, $response->json('field_map'));
        $this->assertSame(LeadExport::MODE_MAPPED, $response->json('mode'));
    }

    public function testStoreWithMissingTemplateIsRejected(): void
    {
        $response = $this->actingAs($this->getUser())
            ->postJson('api/settings/lead-exports', [
                'name' => 'Bad Template',
                'template_id' => 999999,
            ]);

        $response->assertStatus(422);
    }

    public function testUpdatePersistsFieldsAndActive(): void
    {
        $leadExport = LeadExport::query()->create(['name' => 'Editable', 'type' => 'lead']);

        $response = $this->actingAs($this->getUser())
            ->putJson('api/settings/lead-exports/' . $leadExport->id, [
                'name' => 'Editable',
                'active' => true,
                'mode' => LeadExport::MODE_MAPPED,
                'format' => 'json',
                'url' => 'https://crm.example.com/leads',
                'password' => 'secret-token',
                'headers' => ['X-Api-Key' => 'abc123'],
                'field_map' => [['destination' => 'email', 'label' => 'Email', 'type' => 'string']],
                'config' => [],
            ]);

        $response->assertStatus(200);
        $leadExport->refresh();
        $this->assertTrue($leadExport->active);
        $this->assertSame('https://crm.example.com/leads', $leadExport->url);
        $this->assertSame('secret-token', $leadExport->password);
        $this->assertCount(1, $leadExport->field_map);

        // The secret is never returned; only its presence is surfaced.
        $this->assertArrayNotHasKey('password', $response->json());
        $this->assertTrue($response->json('has_password'));
    }

    public function testUpdateRequiresUrlWhenActive(): void
    {
        $leadExport = LeadExport::query()->create(['name' => 'Needs URL', 'type' => 'lead']);

        $response = $this->actingAs($this->getUser())
            ->putJson('api/settings/lead-exports/' . $leadExport->id, [
                'name' => 'Needs URL',
                'active' => true,
                'mode' => LeadExport::MODE_PASSTHROUGH,
                'format' => 'json',
            ]);

        $response->assertStatus(422);
    }

    public function testShowReturnsDocsUrlAndDataOptions(): void
    {
        $leadExport = LeadExport::query()->create(['name' => 'Shown', 'type' => 'lead']);

        $response = $this->actingAs($this->getUser())
            ->getJson('api/settings/lead-exports/' . $leadExport->id);

        $response->assertStatus(200);
        $this->assertStringContainsString('/docs', $response->json('docs_url'));
        $this->assertNotEmpty($response->json('data_options.modes'));
        $this->assertNotEmpty($response->json('data_options.field_types'));
        $this->assertFalse($response->json('has_password'));
    }

    public function testDestroyRemovesExport(): void
    {
        $leadExport = LeadExport::query()->create(['name' => 'Removable', 'type' => 'lead']);

        $response = $this->actingAs($this->getUser())
            ->deleteJson('api/settings/lead-exports/' . $leadExport->id);

        $response->assertStatus(200);
        $this->assertNull(LeadExport::query()->find($leadExport->id));
    }
}
