<?php

namespace App\Console\Commands;

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

class UpdateRcsDlrStatus extends Command
{
    protected $signature   = 'rcs:update-dlr';
    protected $description = 'Process rcs_dlr table and update rcs_send_numbers status';

    // Map vendor eventType → our status string
    private const EVENT_MAP = [
        'delivered' => 'Delivered',
        'read'      => 'Delivered',   // "read" counts as delivered
        'displayed' => 'Delivered',
        'failed'    => 'Failed',
        'expired'   => 'Failed',
    ];

    public function handle(): void
    {
        $batchSize = 500;
        $totalProcessed = 0;

        try {
            while (true) {
                // Fetch unprocessed DLR records
                $dlrRecords = DB::table('rcs_dlr')
                    ->where('is_processed', 0)
                    ->limit($batchSize)
                    ->get(['id', 'master_job_id', 'event_type', 'dlr_time']);

                $count = $dlrRecords->count();

                if ($count === 0) {
                    break;
                }

                $this->info("Processing {$count} RCS DLR records...");

                $processedIds = [];

                foreach ($dlrRecords as $dlr) {
                    $status = self::EVENT_MAP[strtolower($dlr->event_type)] ?? 'Failed';

                    $deliveredDate = $dlr->dlr_time
                        ? strtotime($dlr->dlr_time)
                        : time();

                    Log::info('[RCS DLR CMD] Processing DLR record', [
                        'dlr_id'        => $dlr->id,
                        'master_job_id' => $dlr->master_job_id,
                        'event_type'    => $dlr->event_type,
                        'mapped_status' => $status,
                    ]);

                    // Update rcs_send_numbers
                    $sendUpdated = DB::table('rcs_send_numbers')
                        ->where('master_job_id', $dlr->master_job_id)
                        ->where('status', 'Submitted')
                        ->update([
                            'status'         => $status,
                            'delivered_date' => $deliveredDate,
                            'updated_at'     => now(),
                        ]);

                    // Also update rcs_schedule_send_numbers
                    $schedUpdated = DB::table('rcs_schedule_send_numbers')
                        ->where('master_job_id', $dlr->master_job_id)
                        ->where('status', 'Submitted')
                        ->update([
                            'status'         => $status,
                            'delivered_date' => $deliveredDate,
                            'updated_at'     => now(),
                        ]);

                    Log::info('[RCS DLR CMD] DB update result', [
                        'master_job_id'           => $dlr->master_job_id,
                        'status_set'              => $status,
                        'rcs_send_numbers_rows'   => $sendUpdated,
                        'rcs_schedule_rows'       => $schedUpdated,
                    ]);

                    $processedIds[] = $dlr->id;
                }

                // Mark processed in chunks
                if (!empty($processedIds)) {
                    foreach (array_chunk($processedIds, 100) as $chunk) {
                        DB::table('rcs_dlr')
                            ->whereIn('id', $chunk)
                            ->update(['is_processed' => 1, 'updated_at' => now()]);
                    }

                    $totalProcessed += count($processedIds);
                    $this->info("Marked " . count($processedIds) . " DLR records as processed.");
                }

                if ($count < $batchSize) {
                    break;
                }
            }

            $this->info("RCS DLR update completed. Total processed: {$totalProcessed}");
            Log::info('[RCS DLR CMD] Completed', ['total_processed' => $totalProcessed]);
        } catch (\Throwable $e) {
            Log::error('[RCS DLR CMD] Error: ' . $e->getMessage());
            $this->error('Error: ' . $e->getMessage());
        }
    }
}
