<?php

namespace App\Console\Commands;

use App\Enums\MediaClassification;
use App\Enums\MediaType;
use App\Enums\VerificationStatus;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Migrate companies, partner media, and verification requests from legacy database';

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

        $legacyConn = DB::connection('mysql_second');
        $legacyCompanies = $legacyConn->table('companies')->get();

        if ($legacyCompanies->isEmpty()) {
            $this->warn('No companies found in legacy database.');

            return;
        }

        $this->withProgressBar($legacyCompanies, function ($legacy) use ($legacyConn) {
            // Find user in NEW database. Legcy enhancer is the user_id.
            $user = DB::table('users')->where('id', $legacy->enhancer)->first();

            // If not found by ID, try by email (sometimes IDs change during user migration if not careful)
            if (! $user) {
                $user = DB::table('users')->where('email', $legacy->email)->first();
            }

            if (! $user) {
                // If user still not found, we skip this company for now as it's orphaned
                return;
            }

            // 1. Migrate Company
            DB::table('companies')->updateOrInsert(
                ['id' => $legacy->id],
                [
                    'user_id' => $user->id,
                    'name' => $legacy->name,
                    'email' => $legacy->email,
                    'address' => $legacy->address,
                    'director_name' => $legacy->director,
                    'director_nik' => $legacy->nick_director,
                    'deed_incorporation' => str()->limit($legacy->deed_of_establishment, 150, ''),
                    'trade_license' => str()->limit($legacy->trade_license, 150, ''),
                    'tax_id_number' => str()->limit($legacy->tax_id_number, 150, ''),
                    'taxable_enterprise' => str()->limit($legacy->taxable_enterprise, 150, ''),
                    'annual_tax_return' => str()->limit($legacy->annual_tax_statement, 150, ''),
                    'domicile_certificate' => str()->limit($legacy->domicile, 150, ''),
                    'profile' => str()->limit($legacy->profile ?? '-', 150, ''),
                    'created_at' => $legacy->created_at ?? now(),
                    'updated_at' => $legacy->updated_at ?? now(),
                    'deleted_at' => $legacy->deleted_at,
                ]
            );

            // 2. Migrate Verification Request
            $status = $this->mapVerificationStatus($legacy->status_edit);
            DB::table('verification_requests')->updateOrInsert(
                ['company_id' => $legacy->id],
                [
                    'submitted_by' => $user->id,
                    'status' => $status,
                    'created_at' => $legacy->created_at ?? now(),
                    'updated_at' => $legacy->updated_at ?? now(),
                ]
            );

            // 3. Migrate Partner Media (from legacy 'media' table matching company ID)
            $legacyMediaList = $legacyConn->table('media')->where('company', $legacy->id)->get();
            foreach ($legacyMediaList as $legacyMedia) {
                DB::table('partner_media')->updateOrInsert(
                    ['id' => $legacyMedia->id],
                    [
                        'company_id' => $legacy->id,
                        'name' => $legacyMedia->name,
                        'address' => $legacyMedia->address,
                        'link' => $this->extractMediaLink($legacyMedia->link),
                        'type' => $this->mapMediaType($legacyMedia->type),
                        'classification' => $this->mapMediaClassification($legacyMedia->classification),
                        'journalism_organization' => $legacyMedia->organization,
                        'press_council_certificate' => $legacyMedia->certificate,
                        'created_at' => $legacyMedia->created_at ?? now(),
                        'updated_at' => $legacyMedia->updated_at ?? now(),
                        'deleted_at' => $legacyMedia->deleted_at,
                    ]
                );
            }
        });

        $this->newLine();
        $this->info('Company migration completed successfully!');
    }

    private function mapVerificationStatus($legacyStatus): int
    {
        return match ((string) $legacyStatus) {
            '1', '3' => VerificationStatus::APPROVED->value,
            '2' => VerificationStatus::REJECTED->value,
            default => VerificationStatus::PENDING->value,
        };
    }

    private function mapMediaType($legacyType): int
    {
        return match (strtolower($legacyType ?? '')) {
            'online' => MediaType::ONLINE->value,
            'cetak' => MediaType::PRINT->value,
            'radio' => MediaType::RADIO->value,
            'televisi' => MediaType::TELEVISION->value,
            default => MediaType::ONLINE->value,
        };
    }

    private function mapMediaClassification($legacyClass): int
    {
        return match (strtolower($legacyClass ?? '')) {
            'lokal' => MediaClassification::LOCAL->value,
            'regional' => MediaClassification::REGIONAL->value,
            'nasional' => MediaClassification::NATIONAL->value,
            default => MediaClassification::LOCAL->value,
        };
    }

    private function extractMediaLink(?string $link): ?string
    {
        if (empty($link)) {
            return null;
        }

        // Find all URLs (starts with http or https)
        preg_match_all('/(https?:\/\/[^\s]+)/i', $link, $matches);

        // If no URL found, return the original string truncated
        if (empty($matches[0])) {
            return Str::limit($link, 50, '');
        }

        // Try to find the main media website URL
        foreach ($matches[0] as $url) {
            $url = rtrim($url, ','); // clean trailing comma if any

            // Skip common non-media-website URLs if there's an alternative
            if (count($matches[0]) > 1 && (
                str_contains($url, 'google.') ||
                str_contains($url, 'drive.') ||
                str_contains($url, 'share.') ||
                str_contains($url, 'bit.ly')
            )) {
                continue;
            }

            return Str::limit($url, 50, '');
        }

        // Fallback to the first URL found
        return Str::limit($matches[0][0], 50, '');
    }
}
