<?php

declare(strict_types=1);

namespace App\Models;

use CodeIgniter\Model;

class VapiAssistantBindingModel extends Model
{
    protected $table            = 'vapi_assistant_bindings';
    protected $primaryKey       = 'id';
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $allowedFields    = [
        'vapi_assistant_id',
        'name',
        'vapi_name',
        'url',
        'selected_doc_ids',
        'assigned_agent_ids',
        'pass_threshold_pct',
        'is_active',
    ];
    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';
    protected $updatedField     = 'updated_at';
    protected $validationRules  = [];
    protected $validationMessages = [];
    protected $skipValidation     = false;

    public function getAllWithCounts(): array
    {
        $rows = $this->db->table('vapi_assistant_bindings vb')
            ->select("vb.*, (SELECT COUNT(*) FROM vapi_call_logs vcl WHERE vcl.binding_id = vb.id) as call_count, vb.assigned_agent_ids")
            ->get()
            ->getResultArray();

        $result = [];
        foreach ($rows as $row) {
            $agentIds = json_decode($row['assigned_agent_ids'] ?? '[]', true);
            $row['assigned_agent_count'] = is_array($agentIds) ? count($agentIds) : 0;
            $result[] = $row;
        }
        return $result;
    }

    public function findByVapiAssistantId(string $vapiId): ?array
    {
        $row = $this->where('vapi_assistant_id', $vapiId)->first();
        return $row ?: null;
    }

    public function listForAgent(int $agentId): array
    {
        $rows = $this->where('is_active', 1)->findAll();
        $result = [];
        foreach ($rows as $row) {
            $agentIds = json_decode($row['assigned_agent_ids'] ?? '[]', true);
            if (is_array($agentIds) && in_array($agentId, $agentIds, true)) {
                $result[] = $row;
            }
        }
        return $result;
    }
}
