<?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()
            ->filter(fn(EnquiryModel $enquiry) => $this->hasSufficientDraftData($enquiry))
            ->each(fn(EnquiryModel $enquiry) => $this->dispatch(new ProcessIncomingEnquiryJob($enquiry)));

        return 0;
    }

    private function hasSufficientDraftData(EnquiryModel $enquiry): bool
    {
        if ($enquiry->status_id > 0) {
            return true;
        }

        $draftQuestions = $enquiry->form?->questions
            ->filter(fn($q) => !empty($q->data['include_in_draft']));

        if (!$draftQuestions || $draftQuestions->isEmpty()) {
            return false;
        }

        $details = is_array($enquiry->details) ? $enquiry->details : [];

        return $draftQuestions->contains(fn($q) => !empty($details[$q->id]));
    }
}
