<?php

namespace Tests\Tenant;

use Database\Seeders\Tenant\SocialMediaSettingSeeder;
use Illuminate\Support\Facades\Event;
use Mtc\MercuryDataModels\Events\SettingUpdated;
use Mtc\MercuryDataModels\Setting;
use Tests\TenantTestCase;

class SocialMediaSettingSeederTest extends TenantTestCase
{
    protected bool $useTestSettingRepository = false;

    private const SOCIAL_CONFIG_KEYS = [
        'app-socials-facebook',
        'app-socials-twitter',
        'app-socials-youtube',
        'app-socials-instagram',
        'app-socials-linkedin',
        'app-socials-tiktok',
    ];

    public function testSeedsTheFullSetOfSocialMediaPlatforms()
    {
        (new SocialMediaSettingSeeder())->run();

        foreach (self::SOCIAL_CONFIG_KEYS as $configKey) {
            $setting = Setting::query()->where('config_key', $configKey)->first();

            $this->assertNotNull($setting, "Expected social media setting {$configKey} to be seeded");
            $this->assertEquals('Social Media', $setting->section);
            $this->assertEquals('Social Media Icons', $setting->group);
        }
    }

    public function testBackfillsMissingPlatformsWithoutDuplicatingOrOverwritingValues()
    {
        // Updating an existing setting fires SettingUpdated, whose listeners reach the central
        // database; they are irrelevant to the seeder's data behaviour, so suppress them here.
        Event::fake([SettingUpdated::class]);

        // Simulate a tenant seeded before TikTok existed, with a configured Facebook URL.
        Setting::factory()->create([
            'tab' => 'Site',
            'section' => 'Social Media',
            'group' => 'Social Media Icons',
            'name' => 'Facebook',
            'config_key' => 'app-socials-facebook',
            'type' => 'string',
            'value' => 'https://facebook.com/example',
        ]);

        $this->assertEquals(0, Setting::query()->where('config_key', 'app-socials-tiktok')->count());

        (new SocialMediaSettingSeeder())->run();

        // Missing platform backfilled with an empty default value.
        $tiktok = Setting::query()->where('config_key', 'app-socials-tiktok')->first();
        $this->assertNotNull($tiktok);
        $this->assertSame('', $tiktok->value);

        // Existing platform is not duplicated and its configured value is preserved.
        $facebook = Setting::query()->where('config_key', 'app-socials-facebook')->get();
        $this->assertCount(1, $facebook);
        $this->assertEquals('https://facebook.com/example', $facebook->first()->value);
    }
}
