<?php

namespace App\Console\Commands;

use App\Models\SyncLog;
use Illuminate\Console\Command;

class CleanSyncLogs extends Command
{
    protected $signature = 'sync-logs:clean
                            {--days=30 : Delete logs older than this many days}
                            {--keep=500 : Always keep at least this many of the most recent rows per user}';

    protected $description = 'Delete old sync log entries to prevent table bloat';

    public function handle(): int
    {
        $days = (int) $this->option('days');
        $keep = (int) $this->option('keep');

        $cutoff = now()->subDays($days);

        // Get all distinct user IDs that have sync logs
        $userIds = SyncLog::distinct()->pluck('user_id');

        $totalDeleted = 0;

        foreach ($userIds as $userId) {
            // Find the ID of the $keep-th most-recent log for this user
            $keepId = SyncLog::where('user_id', $userId)
                ->orderByDesc('created_at')
                ->skip($keep)
                ->value('id');

            // Delete logs older than $cutoff, but not if they are among the kept rows
            $query = SyncLog::where('user_id', $userId)
                ->where('created_at', '<', $cutoff);

            if ($keepId !== null) {
                // Only delete rows that are older than the $keep-th row as well
                $query->where('id', '<=', $keepId);
            } else {
                // User has fewer than $keep rows — nothing to delete
                continue;
            }

            $deleted = $query->delete();
            $totalDeleted += $deleted;
        }

        $this->info("Sync log cleanup complete: {$totalDeleted} row(s) deleted (older than {$days} days, keeping last {$keep} per user).");

        return self::SUCCESS;
    }
}
