<?php

namespace App\Console\Commands;

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

class MigrateViewsToResourceViews extends Command
{
    protected $signature = 'views:migrate-to-resource-views';

    protected $description = 'Migrate data from vehicle_views and offer_views tables to resource_views';

    public function handle(): int
    {
        if (!Schema::hasTable('resource_views')) {
            $this->error('resource_views table does not exist. Please run migrations first.');
            return self::FAILURE;
        }

        $this->info('Starting migration of view data to resource_views table...');

        $vehicleCount = $this->migrateVehicleViews();
        $offerCount = $this->migrateOfferViews();

        $this->info("Migration completed!");
        $this->info("- Vehicle views migrated: {$vehicleCount}");
        $this->info("- Offer views migrated: {$offerCount}");

        return self::SUCCESS;
    }

    private function migrateVehicleViews(): int
    {
        if (!Schema::hasTable('vehicle_views')) {
            $this->warn('vehicle_views table does not exist, skipping...');
            return 0;
        }

        $count = 0;
        $this->info('Migrating vehicle_views...');

        DB::table('vehicle_views')
            ->orderBy('id')
            ->chunk(1000, function ($views) use (&$count) {
                $data = $views->map(function ($view) {
                    return [
                        'viewable_type' => 'vehicle',
                        'viewable_id' => $view->vehicle_id,
                        'date' => $view->date,
                        'hits' => $view->hits ?? 0,
                        'quick_view_hits' => $view->quick_view_hits ?? null,
                        'filter_views' => $view->filter_views ?? null,
                        'compare_email_requests' => $view->compare_email_requests ?? null,
                        'created_at' => $view->created_at,
                        'updated_at' => $view->updated_at,
                    ];
                })->toArray();

                DB::table('resource_views')->upsert(
                    $data,
                    ['viewable_type', 'viewable_id', 'date'],
                    ['hits', 'quick_view_hits', 'filter_views', 'compare_email_requests', 'updated_at']
                );

                $count += count($data);
                $this->output->write(".");
            });

        $this->newLine();
        return $count;
    }

    private function migrateOfferViews(): int
    {
        if (!Schema::hasTable('offer_views')) {
            $this->warn('offer_views table does not exist, skipping...');
            return 0;
        }

        $count = 0;
        $this->info('Migrating offer_views...');

        DB::table('offer_views')
            ->orderBy('id')
            ->chunk(1000, function ($views) use (&$count) {
                $data = $views->map(function ($view) {
                    return [
                        'viewable_type' => 'offer',
                        'viewable_id' => $view->offer_id,
                        'date' => $view->date,
                        'hits' => $view->hits ?? 0,
                        'filter_views' => $view->filter_views ?? null,
                        'created_at' => $view->created_at,
                        'updated_at' => $view->updated_at,
                    ];
                })->toArray();

                DB::table('resource_views')->upsert(
                    $data,
                    ['viewable_type', 'viewable_id', 'date'],
                    ['hits', 'filter_views', 'updated_at']
                );

                $count += count($data);
                $this->output->write(".");
            });

        $this->newLine();
        return $count;
    }
}
