<?php

namespace App\Console\Commands;

use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Database\Connection;
use Illuminate\Support\Facades\DB;

#[Signature('migrate:entries:comments {--import-log-table=} {--limit=}')]
class MigrateEntriesComments extends Command
{
    public function handle()
    {
        $logTable = $this->option('import-log-table');
        if( !$logTable ){
            $this->error( 'XenForo import log table required' );
            return self::FAILURE;
        }

        $this->commentsThread( 'entries', 'wp_posts', $logTable );
        $this->commentsThread( 'news', 'wp_posts__news', $logTable );

        $this->info( "Done" );
        return self::SUCCESS;
    }

    private function commentsThread( string $table, string $sourceTable, string $logTable ): void
    {
        $query = DB::table('migrations_logs')
            ->where('source_system', 'wp' )
            ->where('source_table', $sourceTable )
            ->where('target_table', $table );

        if( $limit = $this->option('limit') ){
            $query->limit((int)$limit);
        }

        $rows = $query->get(['source_id', 'target_id']);
        $this->info( "{$rows->count()} need migration logs" );

        $stats = [ 'updated' => 0, 'no_meta' => 0, 'no_new_thread' => 0 ];

        $this->withProgressBar( $rows, function ( $row ) use( $table, $logTable, &$stats ) {

            $oldThreadId = DB::connection('old_wp')
                ->table('postmeta')
                ->where('post_id', $row->source_id )
                ->where('meta_key', 'xf_thread_id')
                ->value('meta_value');

            if( !$oldThreadId ){
                $stats['no_meta']++;
                return;
            }

            $newThreadId = DB::connection('xenforo')
                ->withoutTablePrefix( function( Connection $db ) use( $logTable, $oldThreadId ){
                  return $db->table( $logTable )
                    ->where('content_type', 'thread')
                    ->where('old_id', (string) $oldThreadId )
                    ->value('new_id');
                });

            if( !$newThreadId ){
                $stats['no_new_thread']++;
                return;
            }

            DB::table( $table )->where('id', $row->target_id )->update([
                'comments_thread_id' => (int) $newThreadId
            ]);

            $stats['updated']++;
        });

        $this->newLine();
        $this->info( "Updated: {$stats['updated']}, No new thread: {$stats['no_new_thread']}, No meta: {$stats['no_meta']}" );
    }
}
