<?php

namespace App\Console\Commands;

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

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

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

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

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

        // 1. Migrate Classifications first
        $this->info('Migrating classifications for content recap...');
        $legacyRecapClasses = $legacyConn->table('content_recap_classifications')->get();
        $classMapping = [];

        foreach ($legacyRecapClasses as $legacyClass) {
            // Check by name to avoid duplicates in classifications table
            $existing = DB::table('classifications')->where('name', $legacyClass->name)->first();

            if ($existing) {
                $classMapping[$legacyClass->id] = $existing->id;
            } else {
                $newId = DB::table('classifications')->insertGetId([
                    'name' => $legacyClass->name,
                    'is_active' => IsActive::ACTIVE->value,
                    'created_at' => $legacyClass->created_at ?? now(),
                    'updated_at' => $legacyClass->updated_at ?? now(),
                    'deleted_at' => $legacyClass->deleted_at,
                ]);
                $classMapping[$legacyClass->id] = $newId;
            }
        }

        // 2. Migrate Content Recaps
        $this->info('Migrating content recaps...');
        $legacyRecaps = $legacyConn->table('content_recap')->get();

        if ($legacyRecaps->isEmpty()) {
            $this->warn('No content recaps found in legacy database.');

            return;
        }

        $this->withProgressBar($legacyRecaps, function ($legacy) use ($classMapping) {
            $classificationId = $classMapping[$legacy->classification_id] ?? null;

            // Fallback for classification if not found in master table mapping
            if (! $classificationId && $legacy->classification) {
                $classificationId = DB::table('classifications')
                    ->where('name', $legacy->classification)
                    ->value('id');
            }

            // If still no classification, skip or use a default one?
            // The table requires classification_id so we must have one.
            if (! $classificationId) {
                return; // Skip if no classification
            }

            DB::table('content_recaps')->updateOrInsert(
                ['id' => $legacy->id],
                [
                    'classification_id' => $classificationId,
                    'title' => $legacy->title,
                    'link' => Str::limit($legacy->link, 50, ''),
                    'posting_date' => $legacy->posting_date === '0000-00-00' ? now()->toDateString() : $legacy->posting_date,
                    'type' => $this->mapContentType($legacy->content_type),
                    'channel' => $this->mapChannel($legacy->channel),
                    'social_media' => $this->mapSocialMedia($legacy->social_media),
                    'created_at' => $legacy->created_at ?? now(),
                    'updated_at' => $legacy->updated_at ?? now(),
                    'deleted_at' => $legacy->deleted_at,
                ]
            );
        });
        $this->newLine();

        $this->info('Content recap migration completed successfully!');
    }

    private function mapContentType(?string $legacyType): ?int
    {
        return match (strtolower($legacyType ?? '')) {
            'foto' => ContentType::FOTO->value,
            'grafis' => ContentType::GRAPHIC->value,
            'audio video' => ContentType::VIDEO->value,
            default => null,
        };
    }

    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,
        };
    }

    private function mapSocialMedia(?string $legacySocial): int
    {
        return match (strtolower($legacySocial ?? '')) {
            'ppid diskominfo purwakarta' => SocialMedia::PPID_DISKOMINFO_PURWAKARTA->value,
            'diskominfo purwakarta' => SocialMedia::DISKOMINFO_PURWAKARTA->value,
            'purwakarta saber hoaks' => SocialMedia::PURWAKARTA_SABER_HOAKS->value,
            default => SocialMedia::DISKOMINFO_PURWAKARTA->value,
        };
    }
}
