<?php

namespace App\Domains\Analytics\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\DB;

class RollupHourlyJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable;

    public function handle(): void
    {
        $targetHour = now()->startOfHour()->subHour();
        $nextHour = $targetHour->copy()->addHour();

        DB::statement("
            INSERT INTO clicks_hourly (link_id, hour, country, device, count, unique_visitors)
            SELECT
                link_id,
                DATE_FORMAT(clicked_at, '%Y-%m-%d %H:00:00') AS hour,
                COALESCE(country, '') AS country,
                COALESCE(device, 'unknown') AS device,
                COUNT(*) AS count,
                COUNT(DISTINCT ip_hash) AS unique_visitors
            FROM clicks
            WHERE clicked_at >= ? AND clicked_at < ?
            GROUP BY link_id, hour, country, device
            ON DUPLICATE KEY UPDATE
                count = count + VALUES(count),
                unique_visitors = GREATEST(unique_visitors, VALUES(unique_visitors))
        ", [$targetHour, $nextHour]);
    }
}
