<?php

namespace App\Console\Commands;

use App\Facades\Settings;
use Carbon\Carbon;
use Illuminate\Support\Facades\App;
use Mtc\Crm\Contracts\EnquiryModel;
use App\Jobs\ProcessIncomingEnquiryJob;
use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Mtc\Crm\Models\Scopes\OnlySubmitted;

class IngestEnquiries extends Command
{
    use DispatchesJobs;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'enquiries:ingest';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Process new incoming enquiries';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $model = config('crm.enquiry_model');
        $model::query()
            ->withoutGlobalScope(OnlySubmitted::class)
            ->where(fn ($query) => $query->where('status_id', '>', 0)
                ->when(
                    Settings::get('crm-ingest-partial-submissions-minutes'),
                    fn($subQuery) => $subQuery->orWhere(fn($partialQuery) => $partialQuery->where('status_id', 0)
                        ->where('updated_at', '<=', Carbon::now()
                            ->subMinutes(Settings::get('crm-ingest-partial-submissions-minutes'))))
                ))
            ->whereNull('ingested_at')
            ->get()
            ->each(fn(EnquiryModel $enquiry) => $this->dispatch(new ProcessIncomingEnquiryJob($enquiry)));

        return 0;
    }
}
