<?php

declare(strict_types=1);

namespace App\Console\Commands;

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

final class AggregateSimilarArtworkAnalyticsCommand extends Command
{
    protected $signature = 'analytics:aggregate-similar-artworks {--date= : Date (Y-m-d), defaults to yesterday}';

    protected $description = 'Aggregate similar artwork analytics into daily counts by algo version';

    public function handle(): int
    {
        $date = $this->option('date')
            ? (string) $this->option('date')
            : now()->subDay()->toDateString();

        $rows = DB::table('similar_artwork_events')
            ->selectRaw('algo_version')
            ->selectRaw("SUM(CASE WHEN event_type = 'impression' THEN 1 ELSE 0 END) AS impressions")
            ->selectRaw("SUM(CASE WHEN event_type = 'click' THEN 1 ELSE 0 END) AS clicks")
            ->whereDate('event_date', $date)
            ->groupBy('algo_version')
            ->get();

        foreach ($rows as $row) {
            $impressions = (int) ($row->impressions ?? 0);
            $clicks = (int) ($row->clicks ?? 0);
            $ctr = $impressions > 0 ? $clicks / $impressions : 0.0;

            DB::table('similar_artwork_daily_metrics')->updateOrInsert(
                [
                    'metric_date' => $date,
                    'algo_version' => (string) $row->algo_version,
                ],
                [
                    'impressions' => $impressions,
                    'clicks' => $clicks,
                    'ctr' => $ctr,
                    'updated_at' => now(),
                    'created_at' => now(),
                ]
            );
        }

        $this->info("Aggregated similar artwork analytics for {$date}.");

        return self::SUCCESS;
    }
}
