<?php

declare(strict_types=1);

namespace App\Models;

use CodeIgniter\Model;

class VapiCallLogModel extends Model
{
    protected $table            = 'vapi_call_logs';
    protected $primaryKey       = 'id';
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $allowedFields    = [
        'binding_id',
        'vapi_call_id',
        'agent_id',
        'started_at',
        'ended_at',
        'duration_seconds',
        'direction',
        'phone_number',
        'transcript',
        'recording_url',
        'call_summary',
        'raw_json',
    ];
    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';
    protected $updatedField     = 'updated_at';
    protected $validationRules  = [];
    protected $validationMessages = [];
    protected $skipValidation     = false;

    public function getForBinding(int $bindingId): array
    {
        return $this->where('binding_id', $bindingId)
            ->orderBy('started_at', 'DESC')
            ->findAll();
    }

    public function getForAgent(int $agentId): array
    {
        $builder = $this->db->table('vapi_call_logs vcl')
            ->select('vcl.*, vb.name AS binding_name, vb.vapi_assistant_id, vb.url')
            ->join('vapi_assistant_bindings vb', 'vcl.binding_id = vb.id', 'left')
            ->groupStart()
                ->where('vcl.agent_id', $agentId)
                ->orWhere("JSON_CONTAINS(vb.assigned_agent_ids, " . $this->db->escape((string) $agentId) . ")")
            ->groupEnd()
            ->orderBy('vcl.started_at', 'DESC');

        return $builder->get()->getResultArray();
    }

    public function getWithScore(int $id): ?array
    {
        $row = $this->db->table('vapi_call_logs vcl')
            ->select('vcl.*, vcs.score_pct AS score_pct, vcs.pass_threshold_pct AS pass_threshold_pct, vcs.breakdown_json AS breakdown_json, vcs.ai_feedback AS ai_feedback')
            ->join('vapi_call_scores vcs', 'vcs.call_log_id = vcl.id', 'left')
            ->where('vcl.id', $id)
            ->get()
            ->getRowArray();

        return $row ?: null;
    }

    public function findByVapiCallId(string $vapiCallId): ?array
    {
        $row = $this->where('vapi_call_id', $vapiCallId)->first();
        return $row ?: null;
    }
}
