<?php

namespace App\Console\Commands;

use App\Helpers\MigrationHelpers;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

#[Signature('migrate:reviews:execute {--limit=}')]
class MigrateReviewsExecute extends Command
{

    private function migrateReview( $post, array &$stats ): void
    {
        $exists = DB::table('migrations_logs')
            ->where('source_system', 'wp')
            ->where('source_table', 'wp_posts__reviews')
            ->where('source_id', $post->ID )
            ->exists();

        if( $exists )
            return;

        $meta = DB::connection('old_wp')
            ->table('postmeta')
            ->where('post_id', $post->ID)
            ->whereIn('meta_key', ['reviews_post_link', 'review_rating'])
            ->pluck('meta_value', 'meta_key')
        ;

        $linkedWpPostId = $meta['reviews_post_link'] ?? null;
        if( !$linkedWpPostId ){
            $stats['missing_entry']++;
            return;
        }

        $entryId = DB::table('migrations_logs')
            ->where('source_system', 'wp')
            ->where('source_table', 'wp_posts')
            ->where('source_id', (int) $linkedWpPostId )
            ->where('target_table', 'entries')
            ->value('target_id');

        if( !$entryId ){
            $stats['missing_entry']++;
            return;
        }

        $userId = DB::table('migration_user_plan')
            ->where('wp_user_id', $post->post_author )
            ->value('user_id');

        if( !$userId ){
            $stats['missing_author']++;
            return;
        }

        $rating = $meta['review_rating'] ?? null;
        if( $rating === null || $rating === '' ){
            $stats['missing_rating']++;
            return;
        }

        $description = trim($post->post_content) === '' ? '' : MigrationHelpers::htmlToMarkdown($post->post_content);

        $reviewId = DB::table('entry_reviews')->insertGetId([
            'entry_id' => $entryId,
            'title' => $post->post_title,
            'rating' => (int) $rating,
            'description' => $description,
            'user_id' => $userId,
            'created_at' => $post->post_date,
            'updated_at' => $post->post_modified,
        ]);

        DB::table('migrations_logs')->insert([
            'source_system' => 'wp',
            'source_table' => 'wp_posts__reviews',
            'source_id' => $post->ID,
            'target_table' => 'entry_reviews',
            'target_id' => $reviewId,
            'status' => 'done',
            'migrated_at' => now(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $stats['created']++;
    }

    public function handle(): int
    {
        $query = DB::connection('old_wp')
            ->table('posts')
            ->where('post_type', 'reviews')
            ->where('post_status', 'publish')
        ;

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

        $posts = $query->select('ID', 'post_title', 'post_content', 'post_author', 'post_date', 'post_modified' )->get();
        $this->info("{$posts->count()} reviews found.");

        $stats = ['created' => 0, 'missing_entry' => 0, 'missing_author' => 0, 'missing_rating' => 0 ];

        $this->withProgressBar($posts, function($post) use (&$stats){
            $this->migrateReview($post, $stats);
        });

        $this->newLine();
        $this->info("{$stats['created']} reviews created. {$stats['missing_entry']} missing entry. {$stats['missing_author']} missing author. {$stats['missing_rating']} missing rating.");
        return self::SUCCESS;
    }
}
