<?php

    namespace App\Console\Commands;

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

    class CleanUpJobMonitors extends Command
    {
        protected $signature   = 'jobs:cleanup-monitors';
        protected $description = 'Clean up completed job monitors and related batches every 30 minutes';

        /**
         * @throws Throwable
         */
        public function handle()
        {
            DB::transaction(function () {
                // 1. Collect batch_ids where status is "done"
                $batchIds = DB::table('job_monitors')
                    ->where('status', 'done')
                    ->whereNotNull('batch_id')
                    ->pluck('batch_id');

                // 2. Delete job_monitors where status is "done"
                DB::table('job_monitors')
                    ->where(function ($query) use ($batchIds) {
                        $query->where('status', 'done')
                            ->whereIn('batch_id', $batchIds);
                    })
                    ->orWhereNull('batch_id') // also delete where batch_id is NULL
                    ->delete();

                // 3. Delete related job_batches (only if we have batchIds)
                if ($batchIds->isNotEmpty()) {
                    DB::table('job_batches')
                        ->whereIn('id', $batchIds)
                        ->delete();
                }

                $this->info("Cleaned up completed job monitors, orphaned monitors, and related job batches.");
            });
        }

    }
