<?php

namespace App\Jobs;

use App\Models\Assignment;
use App\Models\User;
use App\Services\WhatsAppService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;

class WhatsAppJob implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new job instance.
     */
    public function __construct(
        private User $user,
        private string $type,
        private ?Assignment $assignment = null
    ) {}

    /**
     * Execute the job.
     */
    public function handle(WhatsAppService $whatsAppService): void
    {
        if (!$this->user->canReceiveAutomatedFeatures()) {
            return;
        }

        // Check quiet hours
        $preferences = $this->user->preferences;
        if ($preferences && $preferences->isQuietHours()) {
            Log::info("WhatsApp notification skipped due to quiet hours for user {$this->user->id}");
            return;
        }

        $sent = false;

        switch ($this->type) {
            case 'due_date_approaching':
                if ($this->assignment) {
                    $sent = $whatsAppService->sendDueDateApproaching($this->assignment);
                }
                break;

            case 'overdue':
                if ($this->assignment) {
                    $sent = $whatsAppService->sendOverdue($this->assignment);
                }
                break;
        }

        if ($sent) {
            Log::info("WhatsApp notification sent to user {$this->user->id} for type {$this->type}");
        }
    }
}
