<?php

namespace App\Commands;

use App\Services\DispatchService;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;

class DispatchCareRequests extends BaseCommand
{
    protected $group='TibaLeta'; protected $name='tibaleta:dispatch'; protected $description='Expires stale offers and matches waiting care requests.';
    public function run(array $params)
    {
        $db=db_connect(); $now=date('Y-m-d H:i:s');
        $db->table('care_request_assignments')->where('status','offered')->where('expires_at <',$now)->update(['status'=>'expired','updated_at'=>$now]);
        $requests=$db->table('care_requests')->select('id')->whereIn('status',['requested','matching','offered'])->where('assigned_practitioner_id',null)->orderBy('created_at')->limit(100)->get()->getResultArray();
        $dispatch=new DispatchService(); $matched=0; foreach($requests as $r){if($dispatch->assignBest((int)$r['id']))$matched++;}
        CLI::write('Processed '.count($requests).' waiting requests; matched '.$matched.'.','green');
    }
}
