<?php

namespace App\Console\Commands;

use App\Enums\ApprovalStatus;
use App\Enums\CooperationStatus;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Migrate cooperation data, proposals, and orders from legacy database';

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

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

        // 1. Migrate media_orders -> cooperations & task_assignments
        $this->info('Migrating media_orders...');
        $legacyOrders = $legacyConn->table('media_orders')->get();
        $this->withProgressBar($legacyOrders, function ($legacy) {
            $status = $legacy->deleted_at ? CooperationStatus::COMPLETED->value : CooperationStatus::ASSIGNMENT->value;

            DB::table('cooperations')->updateOrInsert(
                ['id' => $legacy->id],
                [
                    'title' => Str::limit($legacy->name, 200),
                    'initial_submission_date' => $legacy->begin,
                    'final_submission_date' => $legacy->end,
                    'description' => $legacy->description ?? '-',
                    'status' => $status,
                    'created_at' => $legacy->created_at ?? now(),
                    'updated_at' => $legacy->updated_at ?? now(),
                    'deleted_at' => $legacy->deleted_at,
                ]
            );

            // Task Assignment
            DB::table('task_assignments')->updateOrInsert(
                ['id' => $legacy->id],
                [
                    'cooperation_id' => $legacy->id,
                    'start_date' => $legacy->begin,
                    'end_date' => $legacy->end,
                    'task_description' => $legacy->description ?? '-',
                    'report_amount' => $legacy->amount_report ?? 1,
                    'created_at' => $legacy->created_at ?? now(),
                    'updated_at' => $legacy->updated_at ?? now(),
                ]
            );

            // Pivot Media
            if ($legacy->media) {
                $mediaIds = explode(',', $legacy->media);
                $statuses = explode(',', $legacy->status);
                foreach ($mediaIds as $index => $mediaId) {
                    $mediaId = trim($mediaId);
                    if (empty($mediaId)) {
                        continue;
                    }

                    $mediaStatus = isset($statuses[$index]) ? trim($statuses[$index]) : '1';
                    $approval = $this->mapApprovalStatus($mediaStatus);

                    DB::table('cooperation_media')->updateOrInsert(
                        ['cooperation_id' => $legacy->id, 'partner_media_id' => $mediaId],
                        ['status' => $approval, 'created_at' => $legacy->created_at ?? now(), 'updated_at' => $legacy->updated_at ?? now()]
                    );

                    DB::table('media_task_assignment')->updateOrInsert(
                        ['task_assignment_id' => $legacy->id, 'partner_media_id' => $mediaId],
                        ['status' => $approval, 'created_at' => $legacy->created_at ?? now(), 'updated_at' => $legacy->updated_at ?? now()]
                    );
                }
            }
        });
        $this->newLine();

        // 2. Migrate media_cooperation -> cooperations & task_assignments
        $this->info('Migrating media_cooperation...');
        $legacyCoops = $legacyConn->table('media_cooperation')->get();
        $this->withProgressBar($legacyCoops, function ($legacy) use ($offset) {
            $newId = $legacy->id + $offset;
            $status = $legacy->deleted_at ? CooperationStatus::COMPLETED->value : CooperationStatus::PENDING->value;

            DB::table('cooperations')->updateOrInsert(
                ['id' => $newId],
                [
                    'title' => Str::limit($legacy->name, 200),
                    'initial_submission_date' => $legacy->begin,
                    'final_submission_date' => $legacy->end,
                    'description' => $legacy->description ?? '-',
                    'status' => $status,
                    'created_at' => $legacy->created_at ?? now(),
                    'updated_at' => $legacy->updated_at ?? now(),
                    'deleted_at' => $legacy->deleted_at,
                ]
            );

            // Task Assignment
            DB::table('task_assignments')->updateOrInsert(
                ['id' => $newId],
                [
                    'cooperation_id' => $newId,
                    'start_date' => $legacy->begin,
                    'end_date' => $legacy->end,
                    'task_description' => $legacy->description ?? '-',
                    'report_amount' => 1,
                    'created_at' => $legacy->created_at ?? now(),
                    'updated_at' => $legacy->updated_at ?? now(),
                ]
            );

            // Pivot Media
            if ($legacy->media) {
                $mediaIds = explode(',', $legacy->media);
                foreach ($mediaIds as $mediaId) {
                    $mediaId = trim($mediaId);
                    if (empty($mediaId)) {
                        continue;
                    }

                    DB::table('cooperation_media')->updateOrInsert(
                        ['cooperation_id' => $newId, 'partner_media_id' => $mediaId],
                        ['status' => ApprovalStatus::PENDING->value, 'created_at' => $legacy->created_at ?? now(), 'updated_at' => $legacy->updated_at ?? now()]
                    );

                    DB::table('media_task_assignment')->updateOrInsert(
                        ['task_assignment_id' => $newId, 'partner_media_id' => $mediaId],
                        ['status' => ApprovalStatus::PENDING->value, 'created_at' => $legacy->created_at ?? now(), 'updated_at' => $legacy->updated_at ?? now()]
                    );
                }
            }
        });
        $this->newLine();

        // 3. Migrate proposals
        $this->info('Migrating proposals...');
        $legacyProposals = $legacyConn->table('propose_media_cooperation')->get();
        $this->withProgressBar($legacyProposals, function ($legacy) use ($offset) {
            $media = DB::table('partner_media')
                ->join('companies', 'partner_media.company_id', '=', 'companies.id')
                ->where('companies.user_id', $legacy->enhancer)
                ->select('partner_media.id')
                ->first();

            if (! $media) {
                return;
            }

            DB::table('cooperation_proposals')->updateOrInsert(
                ['id' => $legacy->id],
                [
                    'cooperation_id' => $legacy->media_cooperation_id + $offset,
                    'partner_media_id' => $media->id,
                    'description' => $legacy->rejection_reason ?? '-',
                    'e_catalog' => Str::limit($legacy->e_catalog, 200),
                    'status' => $this->mapApprovalStatus($legacy->status),
                    'submitted_at' => $legacy->created_at ?? now(),
                    'responded_at' => $legacy->updated_at,
                    'created_at' => $legacy->created_at ?? now(),
                    'updated_at' => $legacy->updated_at ?? now(),
                ]
            );
        });
        $this->newLine();

        // 4. Migrate reports
        $this->info('Migrating reports...');
        $legacyReports = $legacyConn->table('reports')->get();
        $this->withProgressBar($legacyReports, function ($legacy) {
            // Find media_task_assignment_id
            // We assume media_order in reports refers to media_orders table primarily
            $assignment = DB::table('media_task_assignment')
                ->where('task_assignment_id', $legacy->media_order)
                ->where('partner_media_id', $legacy->media)
                ->first();

            if (! $assignment) {
                return;
            }

            DB::table('reports')->updateOrInsert(
                ['id' => $legacy->id],
                [
                    'media_task_assignment_id' => $assignment->id,
                    'title' => $legacy->title,
                    'publication_date' => $legacy->broadcast ?? $legacy->created_at ?? now(),
                    'link' => Str::limit($legacy->link, 50),
                    'description' => 'Legacy Proof: '.($legacy->proof ?? '-'),
                    'status' => $this->mapReportStatus($legacy->status),
                    'created_at' => $legacy->created_at ?? now(),
                    'updated_at' => $legacy->updated_at ?? now(),
                    'deleted_at' => $legacy->deleted_at,
                ]
            );
        });
        $this->newLine();

        $this->info('Cooperation and report migration completed!');
    }

    private function mapApprovalStatus($legacy): int
    {
        return match ((string) $legacy) {
            '1', '4' => ApprovalStatus::ACCEPTED->value,
            '2', '0' => ApprovalStatus::REJECTED->value, // Assume 0 is rejected/inactive in some contexts, but let's see
            default => ApprovalStatus::PENDING->value,
        };
    }

    private function mapReportStatus($legacy): int
    {
        return match ((string) $legacy) {
            '1' => ApprovalStatus::ACCEPTED->value,
            '2' => ApprovalStatus::REJECTED->value,
            default => ApprovalStatus::PENDING->value,
        };
    }
}
