<?php

namespace App\Console\Commands;

use App\Models\Branch;
use App\Models\Organization;
use App\Services\Care\CareQueueBridge;
use App\Services\Care\CareQueueContexts;
use Illuminate\Console\Command;

/**
 * Backfill Care Queue Engine tickets for waiters that never received one
 * (e.g. demo seed or patients checked in before service queues were enabled).
 */
class SyncCareQueueTicketsCommand extends Command
{
    protected $signature = 'care:queue-sync-tickets
                            {--organization= : Organization id (default: all with service queues on)}
                            {--branch= : Limit to one Care branch id}
                            {--context=consultation : consultation|pharmacy|laboratory|billing|all}
                            {--limit=100 : Max tickets to issue per branch+context}';

    protected $description = 'Issue missing Care Queue Engine tickets for waiting lists';

    public function handle(CareQueueBridge $bridge): int
    {
        $contextOpt = strtolower((string) $this->option('context'));
        $contexts = $contextOpt === 'all'
            ? array_values(array_filter(
                array_keys(CareQueueContexts::departments()),
                fn (string $c) => $c !== CareQueueContexts::RECEPTION,
            ))
            : [$contextOpt];

        foreach ($contexts as $context) {
            if ($context !== CareQueueContexts::RECEPTION && ! CareQueueContexts::isDepartment($context) && ! CareQueueContexts::isSpecialty($context)) {
                $this->error("Unknown context: {$context}");

                return self::FAILURE;
            }
        }

        $orgQuery = Organization::query();
        if ($this->option('organization')) {
            $orgQuery->where('id', (int) $this->option('organization'));
        }

        $limit = max(1, (int) $this->option('limit'));
        $branchFilter = $this->option('branch') ? (int) $this->option('branch') : null;
        $total = 0;

        foreach ($orgQuery->cursor() as $organization) {
            if (! $bridge->isEnabled($organization)) {
                continue;
            }

            $branches = Branch::owned((string) $organization->owner_ref)
                ->where('organization_id', $organization->id)
                ->where('is_active', true)
                ->when($branchFilter, fn ($q) => $q->where('id', $branchFilter))
                ->orderBy('id')
                ->get();

            foreach ($branches as $branch) {
                foreach ($contexts as $context) {
                    $issued = $bridge->syncMissingTickets($organization, $context, (int) $branch->id, $limit);
                    if ($issued > 0) {
                        $this->info(sprintf(
                            'org=%d branch=%d (%s) context=%s issued=%d',
                            $organization->id,
                            $branch->id,
                            $branch->name,
                            $context,
                            $issued,
                        ));
                    }
                    $total += $issued;
                }
            }
        }

        $this->info("Done. Issued {$total} ticket(s).");

        return self::SUCCESS;
    }
}
