<?php

namespace App\Console\Commands;

use App\Enums\Channel;
use App\Enums\IsActive;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class MigrateMediaMonitoringCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'migrate:media-monitoring';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Migrate media monitoring data from legacy database';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Starting media monitoring migration...');

        $legacyConn = DB::connection('mysql_second');

        // Get legacy monitorings
        $legacyMonitorings = $legacyConn->table('media_monitorings')->get();

        if ($legacyMonitorings->isEmpty()) {
            $this->warn('No media monitorings found in legacy database.');

            return;
        }

        $this->withProgressBar($legacyMonitorings, function ($legacy) {
            // Main record
            DB::table('media_monitorings')->updateOrInsert(
                ['id' => $legacy->id],
                [
                    'code' => Str::limit($legacy->code, 10, ''),
                    'media_name' => Str::limit($legacy->media_name, 50, ''),
                    'title' => $legacy->title,
                    'channel' => $this->mapChannel($legacy->channel),
                    'writter' => Str::limit($legacy->writter, 50, ''),
                    'link' => $legacy->link,
                    'news_page' => Str::limit($legacy->news_page, 20, ''),
                    'quote' => $legacy->quote,
                    'content' => $legacy->content,
                    'influencer' => Str::limit($legacy->influencer, 50, ''),
                    'keyword' => Str::limit($legacy->keyword, 100, ''),
                    'release_date' => $legacy->release_date,
                    'created_at' => $legacy->created_at ?? now(),
                    'updated_at' => $legacy->updated_at ?? now(),
                    'deleted_at' => $legacy->deleted_at,
                ]
            );

            // Handle Theme (Insert into themes table if not exists)
            $themeName = trim($legacy->theme);
            if (! empty($themeName)) {
                $themeName = Str::limit($themeName, 50, '');

                // Ensure theme exists in master table
                DB::table('themes')->updateOrInsert(
                    ['name' => $themeName],
                    [
                        'is_active' => IsActive::ACTIVE->value,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]
                );

                $themeId = DB::table('themes')->where('name', $themeName)->value('id');

                // Link to pivot table
                if ($themeId) {
                    DB::table('media_monitoring_theme')->updateOrInsert(
                        [
                            'media_monitoring_id' => $legacy->id,
                            'theme_id' => $themeId,
                        ]
                    );
                }
            }
        });
        $this->newLine();

        $this->info('Media monitoring migration completed successfully!');
    }

    private function mapChannel(?string $legacyChannel): int
    {
        return match (strtolower($legacyChannel ?? '')) {
            'website' => Channel::WEBSITE->value,
            'tiktok' => Channel::TIKTOK->value,
            'youtube' => Channel::YOUTUBE->value,
            'facebook' => Channel::FACEBOOK->value,
            'instagram' => Channel::INSTAGRAM->value,
            'twitter' => Channel::TWITTER->value,
            default => Channel::WEBSITE->value,
        };
    }
}
