<?php

namespace Database\Seeders;

use App\Models\Agency\Agency;
use App\Models\Agency\Currency;
use App\Models\Agency\Marketplace;
use App\Models\Definition\Language;
use App\Models\Product\Product;
use App\Models\Definition\Country;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;

class MarketplaceSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $agencies = Agency::all();

        // Common languages we will query
        $languagesCache = Language::all()->keyBy(function($lang) {
            return strtoupper($lang->code);
        });

        foreach ($agencies as $agency) {
            // Currencies for this agency
            $currenciesCache = Currency::where('agency_id', $agency->id)->get()->keyBy('code');

            $defaultLang = $languagesCache->first();
            $defaultCurr = $currenciesCache->first();

            // The 8 marketplaces config
            $marketplacesConfig = [
                [
                    'slug' => 'yerli-pazar',
                    'name' => 'Yerli Pazar',
                    'default_lang' => 'TR',
                    'langs' => ['TR'],
                    'default_curr' => 'TRY',
                    'is_local_only' => true,
                    'countries' => []
                ],
                [
                    'slug' => 'kuzey-amerika',
                    'name' => 'Kuzey Amerika',
                    'default_lang' => 'EN',
                    'langs' => ['EN', 'ES', 'FR'],
                    'default_curr' => 'USD',
                    'is_local_only' => false,
                    'countries' => ['US', 'CA', 'MX']
                ],
                [
                    'slug' => 'guney-amerika',
                    'name' => 'Güney Amerika',
                    'default_lang' => 'ES',
                    'langs' => ['ES', 'PT', 'EN'],
                    'default_curr' => 'USD',
                    'is_local_only' => false,
                    'countries' => ['AR', 'BR', 'CL', 'CO', 'PE', 'VE', 'UY', 'PY', 'BO', 'EC']
                ],
                [
                    'slug' => 'avrupa-balkanlar',
                    'name' => 'Avrupa (Balkanlar)',
                    'default_lang' => 'EN',
                    'langs' => ['EN', 'TR', 'DE'],
                    'default_curr' => 'EUR',
                    'is_local_only' => false,
                    'countries' => ['AL', 'BA', 'BG', 'GR', 'HR', 'ME', 'MK', 'RO', 'RS', 'XK']
                ],
                [
                    'slug' => 'avrupa-schengen',
                    'name' => 'Avrupa (Schengen)',
                    'default_lang' => 'EN',
                    'langs' => ['EN', 'DE', 'FR', 'ES', 'IT', 'NL'],
                    'default_curr' => 'EUR',
                    'is_local_only' => false,
                    'countries' => ['AT', 'BE', 'CH', 'CZ', 'DE', 'DK', 'EE', 'ES', 'FI', 'FR', 'GR', 'HU', 'IS', 'IT', 'LI', 'LT', 'LU', 'LV', 'MT', 'NL', 'NO', 'PL', 'PT', 'SE', 'SI', 'SK']
                ],
                [
                    'slug' => 'asya',
                    'name' => 'Asya',
                    'default_lang' => 'EN',
                    'langs' => ['EN', 'ZH', 'JA', 'RU'],
                    'default_curr' => 'USD',
                    'is_local_only' => false,
                    'countries' => ['CN', 'JP', 'KR', 'SG', 'MY', 'TH', 'VN', 'ID', 'PH', 'IN', 'PK', 'AZ', 'KZ', 'UZ']
                ],
                [
                    'slug' => 'kuzey-afrika',
                    'name' => 'Kuzey Afrika',
                    'default_lang' => 'AR',
                    'langs' => ['AR', 'FR', 'EN'],
                    'default_curr' => 'USD',
                    'is_local_only' => false,
                    'countries' => ['DZ', 'EG', 'LY', 'MA', 'TN', 'SD']
                ],
                [
                    'slug' => 'guney-afrika',
                    'name' => 'Güney Afrika',
                    'default_lang' => 'EN',
                    'langs' => ['EN'],
                    'default_curr' => 'USD',
                    'is_local_only' => false,
                    'countries' => ['ZA', 'ZM', 'ZW', 'BW', 'NA', 'LS', 'SZ', 'MZ', 'AO']
                ]
            ];

            $createdSlugs = [];

            foreach ($marketplacesConfig as $config) {
                // Determine default language model
                $defLangModel = $languagesCache->get(strtoupper($config['default_lang'])) ?? $defaultLang;
                $defLangId = $defLangModel ? $defLangModel->id : null;

                // Determine default currency model
                $defCurrModel = $currenciesCache->get(strtoupper($config['default_curr'])) ?? $defaultCurr;
                $defCurrId = $defCurrModel ? $defCurrModel->id : null;

                // Update or create Marketplace
                $mp = Marketplace::updateOrCreate(
                    [
                        'agency_id' => $agency->id,
                        'slug' => $config['slug']
                    ],
                    [
                        'name' => $config['name'],
                        'default_language_id' => $defLangId,
                        'default_currency_id' => $defCurrId,
                        'is_local_only' => $config['is_local_only'],
                        'is_active' => true
                    ]
                );

                $createdSlugs[] = $config['slug'];

                // Sync languages
                $langIds = [];
                foreach ($config['langs'] as $lCode) {
                    $lModel = $languagesCache->get(strtoupper($lCode));
                    if ($lModel) {
                        $langIds[] = $lModel->id;
                    }
                }
                if (empty($langIds) && $defaultLang) {
                    $langIds[] = $defaultLang->id;
                }
                $mp->languages()->sync($langIds);

                // Sync countries
                if ($config['is_local_only']) {
                    $mp->countries()->detach();
                } else {
                    $countryIds = Country::whereIn('code', $config['countries'])->pluck('id')->toArray();
                    $mp->countries()->sync($countryIds);
                }

                // Sync products
                $products = Product::where('agency_id', $agency->id)->get();
                if ($products->isNotEmpty()) {
                    $productIds = $products->pluck('id')->toArray();
                    $mp->products()->sync($productIds);
                }
            }

            // Clean up any old marketplaces for this agency
            $toDelete = Marketplace::where('agency_id', $agency->id)
                ->whereNotIn('slug', $createdSlugs)
                ->get();

            foreach ($toDelete as $oldMp) {
                $oldMp->languages()->detach();
                $oldMp->countries()->detach();
                $oldMp->products()->detach();
                $oldMp->delete();
            }
        }
    }
}
