<?php

namespace App\Console\Commands;

use App\Http\Controllers\SMS\QuickSmsController;
use App\Jobs\CheckSmsStatusJob;
use App\Jobs\ReteySmsJob;
use App\Models\JobsHistory;
use App\Models\SMSActivity;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CheckApiStatusScheduler extends Command
{
    protected $signature = 'check:api-status';
    protected $description = 'Check SMS API delivery status';

    public function handle()
    {
        try {
            $sevenDaysAgo = Carbon::now()->subDays(8);
            $fourDaysAgo = Carbon::now()->subDays(3);
            $threeHoursAgo = Carbon::now()->subHours(3);

            $smsData = SMSActivity::where('created_at', '>=', $fourDaysAgo)
                ->where(function ($query) use ($threeHoursAgo) {
                    $query->where(function ($q) {
                        $q->whereNull('check_api_status')->orWhere('check_api_status', 'Pending');
                    });
                    $query->orWhere(function ($q) use ($threeHoursAgo) {
                        $q->where('check_api_status', 'UnDelivered')->where('check_api_count', '<', 2)
                            ->where('updated_at', '<=', $threeHoursAgo);
                    });
                })
                ->orderBy('id', 'ASC')
                ->get();


            $messageIds = collect($smsData)->pluck('id')->toArray();
            $chekApiJobs = DB::table('jobs_histories')->select("job_type_id")
                ->where('job_type', 3)
                ->whereIn('job_type_id', $messageIds)->where('status', 0)
                ->get()->keyBy('job_type_id')->toArray();

            foreach ($smsData as $eachSms) {
                if (!isset($chekApiJobs[$eachSms->id])) {
                    dispatch(new CheckSmsStatusJob([
                        'smsData' => $eachSms,
                        'sms_id' => $eachSms->id,
                        'user_id' => $eachSms->user_id,
                        'job_type' => 3, //CheckApiJob
                        'date' => date('Y-m-d', strtotime($eachSms->created_at)),
                    ], new JobsHistory()));
                }
            }


            $min1MinuitAgoFromNow = Carbon::now()->subMinute();
            $failedSms = SMSActivity::where(function ($query) use ($min1MinuitAgoFromNow) {
                $query->where('job_status', 1);
                $query->orWhere(function ($query) use ($min1MinuitAgoFromNow) {
                        $query->where('job_status', 0);
                        $query->where('api_status', 0);
                        $query->where('created_at', '<=', $min1MinuitAgoFromNow);
                    });
            })
                ->where('try_count', 1)
                ->where('created_at', '>=', $sevenDaysAgo)
                ->whereNotIn('api_status', [9000, 1000])
                ->get();

            $failedIds = collect($failedSms)->pluck('id')->toArray();
            $pendingJobs = DB::table('jobs_histories')->select("job_type_id")
                ->where('job_type', 2)
                ->whereIn('job_type_id', $failedIds)->where('status', 0)
                ->get()->keyBy('job_type_id')->toArray();

            foreach ($failedSms as $eachSms) {
                if (!isset($pendingJobs[$eachSms->id])) {
                    dispatch(new ReteySmsJob([
                        'smsData' => $eachSms,
                        'sms_id' => $eachSms->id,
                        'user_id' => $eachSms->user_id,
                        'job_type' => 2, //RetrySMS
                        'date' => date('Y-m-d', strtotime($eachSms->created_at)),
                    ], new JobsHistory()));
                }
            }

            DB::table('schedule_logs')->insert([
                'schedule_name' => $this->signature,
                'ran_at' => now(),
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            // 3️⃣ Keep only last 5 records
            $idsToKeep = DB::table('schedule_logs')
                ->orderBy('ran_at', 'desc')
                ->limit(5)
                ->pluck('id')
                ->toArray();

            DB::table('schedule_logs')
                ->whereNotIn('id', $idsToKeep)
                ->delete();
        }catch (\Exception $exception){
            insertFailLog(0, $exception->getMessage(), null,'Schedular Exception');
        }
    }
}
