<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class ImportWallzCategories extends Command
{
    /**
     * The name and signature of the console command.
     *
     * --connection: database connection name for legacy DB (default: legacy)
     * --table: legacy table name (default: wallz)
     * --chunk: rows per chunk (default: 500)
     */
    protected $signature = 'import:wallz-categories {--connection=legacy} {--table=wallz} {--chunk=500}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Import artwork -> category mappings from legacy wallz table into artwork_category';

    public function handle()
    {
        $conn = $this->option('connection');
        $table = $this->option('table');
        $chunk = (int) $this->option('chunk');

        $this->info("Importing from connection=[{$conn}] table=[{$table}]");

        // Validate connection exists in config
        if (! config()->has('database.connections.' . $conn)) {
            $this->error("Database connection '{$conn}' not configured. Available connections: " . implode(', ', array_keys(config('database.connections'))));
            return 1;
        }

        // Check legacy table exists
        try {
            if (! Schema::connection($conn)->hasTable($table)) {
                $this->error("Table '{$table}' does not exist on connection '{$conn}'.");
                return 1;
            }
        } catch (\Throwable $e) {
            $this->error('Error checking legacy table: ' . $e->getMessage());
            return 1;
        }

        $total = DB::connection($conn)->table($table)->count();
        $this->info("Found {$total} rows in legacy table.");

        $bar = $this->output->createProgressBar($total ?: 0);
        $bar->start();

        try {
            DB::connection($conn)->table($table)
                ->select('id', 'category')
                ->orderBy('id')
                ->chunk($chunk, function ($rows) use ($bar) {
                    $inserts = [];
                    foreach ($rows as $r) {
                        // Skip empty category
                        if (empty($r->category)) continue;
                        $inserts[] = [
                            'artwork_id' => (int) $r->id,
                            'category_id' => (int) $r->category,
                        ];
                    }

                    if (! empty($inserts)) {
                        // Use insertOrIgnore to avoid duplicates
                        DB::table('artwork_category')->insertOrIgnore($inserts);
                    }

                    $bar->advance(count($rows));
                });

            $bar->finish();
            $this->newLine(2);
            $this->info('Import complete.');
            return 0;
        } catch (\Throwable $e) {
            $bar->finish();
            $this->newLine(2);
            $this->error('Import failed: ' . $e->getMessage());
            return 1;
        }
    }
}
