<?php

namespace App\Console\Commands;

use App\Models\FollowUp;
use App\Models\Notification;
use Illuminate\Console\Command;

class SendDueFollowUpNotifications extends Command
{
    protected $signature = 'crm:notify-followups';
    protected $description = 'Create notifications for due and overdue follow-ups';

    public function handle(): int
    {
        FollowUp::query()
            ->where('status', 'pending')
            ->whereNotNull('assigned_to')
            ->where('due_at', '<=', now())
            ->chunkById(100, function ($followUps) {
                foreach ($followUps as $followUp) {
                    $already = Notification::where('user_id', $followUp->assigned_to)
                        ->where('type', 'followup_due')
                        ->whereJsonContains('data->follow_up_id', $followUp->id)
                        ->whereDate('created_at', today())
                        ->exists();

                    if (!$already) {
                        Notification::create([
                            'user_id' => $followUp->assigned_to,
                            'title' => 'Follow-up due',
                            'message' => $followUp->subject,
                            'type' => 'followup_due',
                            'data' => ['follow_up_id' => $followUp->id, 'lead_id' => $followUp->lead_id],
                        ]);
                    }
                }
            });

        $this->info('Due follow-up notifications processed.');

        return self::SUCCESS;
    }
}
