<?php

namespace Tests\Feature\Seeders;

use App\Models\ExportMapTemplate;
use Database\Seeders\Global\GoogleDisplayExportMapTemplateSeed;
use Tests\DatabaseTestCase;

class GoogleDisplayExportMapTemplateSeedTest extends DatabaseTestCase
{
    public function test_it_seeds_the_google_display_vehicles_template()
    {
        (new GoogleDisplayExportMapTemplateSeed())->run();

        $template = ExportMapTemplate::where('title', 'Google Display - Vehicles')->first();

        $this->assertNotNull($template);
        $this->assertTrue($template->is_published);
        $this->assertSame('vehicle', $template->type);
        $this->assertSame('', $template->sales_channel);

        // 20-column agency template, columns and headers aligned by position.
        $this->assertCount(20, $template->columns);
        $this->assertCount(20, $template->headers);

        $this->assertSame('uuid', $template->columns[0]);
        $this->assertSame('ID', $template->headers[0]);
        $this->assertSame('custom1', $template->columns[10]);
        $this->assertSame('Contextual keywords', $template->headers[10]);
        $this->assertSame('custom2', $template->columns[11]);
        $this->assertSame('Item address', $template->headers[11]);

        // Currency rule appends EUR to price (kept first).
        $this->assertCount(4, $template->mapping_rules);
        $this->assertSame('price', $template->mapping_rules[0]['then'][0]['target']);
        $this->assertSame('append', $template->mapping_rules[0]['then'][0]['action']);
        $this->assertSame(' EUR', $template->mapping_rules[0]['then'][0]['value']);

        // Item address (custom2) built from dealership parts via the merge action.
        $this->assertSame('merge', $template->mapping_rules[1]['then'][0]['action']);
        $this->assertSame('custom2', $template->mapping_rules[1]['then'][0]['target']);
        $this->assertSame('dealership.address1', $template->mapping_rules[1]['then'][0]['source']);
        $this->assertSame(', ', $template->mapping_rules[1]['then'][0]['separator']);

        // Contextual keywords (custom1) built via merge.
        $this->assertSame('custom1', $template->mapping_rules[2]['then'][0]['target']);
        $this->assertSame('merge', $template->mapping_rules[2]['then'][0]['action']);

        // Conditional "for sale" token guarded by the scratch slot being non-empty.
        $this->assertSame('kw_make_model', $template->mapping_rules[3]['when']['field']);
        $this->assertSame('is_not_empty', $template->mapping_rules[3]['when']['op']);
        $this->assertSame(' for sale', $template->mapping_rules[3]['then'][0]['value']);
    }

    public function test_it_is_idempotent()
    {
        (new GoogleDisplayExportMapTemplateSeed())->run();
        (new GoogleDisplayExportMapTemplateSeed())->run();

        $this->assertSame(
            1,
            ExportMapTemplate::where('title', 'Google Display - Vehicles')->count()
        );
    }
}
