<?php

namespace App\Console\Commands;

use App\Jobs\NewDealCustomerMessageJob;
use App\Jobs\NewDealCustomerStatusChangeJob;
use App\Jobs\ProcessNewDealSubmissionJob;
use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Mtc\MercuryDataModels\DealBuilder\Deal;
use Mtc\MercuryDataModels\DealBuilder\DealHistory;
use Mtc\MercuryDataModels\DealBuilder\DealMessage;

class SendDealNotifications extends Command
{
    use DispatchesJobs;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'deals:send-notifications';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send customer created deal notifications';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->ingestNewDeals();
        $this->notifyCustomerMessages();
        $this->notifyCustomerStatusChanges();

        return self::SUCCESS;
    }

    private function ingestNewDeals(): void
    {
        Deal::query()
            ->whereNull('ingested_at')
            ->whereDoesntHave('status', fn($query) => $query->whereIn('name', ['Draft', 'Cancelled']))
            ->pluck('id')
            ->each(fn(int $deal_id) => $this->dispatch(new ProcessNewDealSubmissionJob($deal_id)));
    }

    private function notifyCustomerMessages(): void
    {
        DealMessage::query()
            ->whereNull('notification_sent_at')
            ->whereNotNull('customer_id')
            ->pluck('id')
            ->each(fn(int $message_id) => $this->dispatch(new NewDealCustomerMessageJob($message_id)));
    }

    private function notifyCustomerStatusChanges(): void
    {
        DealHistory::query()
            ->whereNull('notification_sent_at')
            ->whereNotNull('customer_id')
            ->pluck('id')
            ->each(fn(int $history_id) => $this->dispatch(new NewDealCustomerStatusChangeJob($history_id)));
    }
}
