<?php

namespace Database\Seeders;

use App\Models\Backoffice\WebsiteObject;
use App\Models\Backoffice\WebsiteObjectLanguage;
use App\Models\Country;
use App\Models\CountryLanguage;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Throwable;

class CountriesSeeder extends Seeder
{
    const LANG_CODE_MAP = [
        'en' => null, // default - not on translations
        'de' => 'deu'
    ];

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $seederData = json_decode(
            Storage::disk('json')->get('countries.json'),
            true
        );

        $languages = LaravelLocalization::getSupportedLanguagesKeys();

        DB::beginTransaction();
        try {
            foreach ($seederData as $countryData) {
                if (Country::where('iso2', $countryData['cca2'])->exists()) {
                    continue;
                }

                $country = new Country();
                $country->iso2 = $countryData['cca2'];
                $country->iso3 = $countryData['cca3'];
                $country->save();

                $wo = new WebsiteObject();
                $wo->object_id = $country->id;
                $wo->object_type = Country::class;
                $wo->content_type = 'country';
                $wo->save();

                foreach ($languages as $lang) {
                    $transLang = self::LANG_CODE_MAP[$lang];
                    $countryName = $transLang ? $countryData['translations'][$transLang]['official'] : $countryData['name']['official'];
                    $commonName = $transLang ? $countryData['translations'][$transLang]['common'] : $countryData['name']['common'];

                    $countryLanguage = new CountryLanguage();
                    $countryLanguage->country_id = $country->id;
                    $countryLanguage->language_id = $lang;
                    $countryLanguage->title = $countryName;
                    $countryLanguage->common_name = $commonName;
                    $countryLanguage->save();

                    $wol = new WebsiteObjectLanguage();
                    $wol->website_object_id = $wo->id;
                    $wol->wo_language_id = $lang;
                    $wol->save();
                }
            }

            DB::commit();
        } catch (Throwable $e) {
            DB::rollBack();
            throw($e);
        }
    }
}
