<?php

namespace Modules\MedBilling\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Modules\MedBilling\Services\ChargeCaptureService;

/**
 * medbill:capture-completed {--date=} {--business=}
 *
 * Drafts charge items for every appointment that was COMPLETED on the given day
 * (default: yesterday). Idempotent — captureForAppointment never duplicates an
 * already-captured source row, so it is safe to run daily (scheduled at 02:00 by
 * MedBillingServiceProvider) or re-run manually.
 *
 * This is the automatic half of charge capture; the on-demand half is the
 * "Capture charges" button on the billing worklist. Both are documented in the
 * README.
 *
 * Fail-soft: a bad appointment is logged and skipped; ClinicCore absence is a
 * clean no-op.
 */
class CaptureCompletedCommand extends Command
{
    protected $signature = 'medbill:capture-completed {--date= : Y-m-d day of completion (default: yesterday)} {--business= : limit to one business_id}';

    protected $description = 'Draft MedBilling charges for appointments completed on a given day (default: yesterday).';

    public function handle(ChargeCaptureService $capture): int
    {
        if (! Schema::hasTable('clc_appointments')) {
            $this->warn('ClinicCore not installed (clc_appointments missing) — nothing to do.');

            return self::SUCCESS;
        }

        $date = $this->option('date') ?: now()->subDay()->toDateString();

        $query = DB::table('clc_appointments')
            ->where('status', 'completed')
            ->whereDate('updated_at', $date);

        if ($this->option('business')) {
            $query->where('business_id', (int) $this->option('business'));
        }

        $appointmentIds = $query->orderBy('id')->pluck('id');

        if ($appointmentIds->isEmpty()) {
            $this->info("No completed appointments found for {$date}.");

            return self::SUCCESS;
        }

        $created = 0;
        $processed = 0;

        foreach ($appointmentIds as $id) {
            try {
                $out = $capture->captureForAppointment((int) $id);
                $created += (int) ($out['created'] ?? 0);
                $processed++;
            } catch (\Throwable $e) {
                \Log::warning("MedBilling capture-completed failed for appointment {$id}: " . $e->getMessage());
            }
        }

        $this->info("MedBilling: processed {$processed} completed appointment(s) for {$date}; drafted {$created} new charge(s).");

        return self::SUCCESS;
    }
}
