<?php

namespace App\Controllers;

use App\Models\AiCallLogModel;

/**
 * Manager-only audit list over ai_call_log — every ClaudeService call,
 * success or failure, with token usage — so a manager can debug what
 * the AI actually said/did and track cost. Read-only; nothing here
 * writes to ai_call_log (see ClaudeService::logCall(), the only writer).
 * Same filter-row/pagination shape as the Activity Log page.
 */
class AiCallLogController extends BaseController
{
    public function index()
    {
        $model = new AiCallLogModel();

        $filters = [
            'feature'   => $this->request->getGet('feature') ?: '',
            'status'    => $this->request->getGet('status') ?: '',
            'date_from' => $this->request->getGet('date_from') ?: '',
            'date_to'   => $this->request->getGet('date_to') ?: '',
        ];

        $model->select('ai_call_log.*, users.full_name as triggered_by_name')
            ->join('users', 'users.id = ai_call_log.triggered_by', 'left');

        if ($filters['feature'] !== '') {
            $model->where('ai_call_log.feature', $filters['feature']);
        }

        if ($filters['status'] === 'success') {
            $model->where('ai_call_log.success', 1);
        } elseif ($filters['status'] === 'failed') {
            $model->where('ai_call_log.success', 0);
        }

        if ($filters['date_from'] !== '') {
            $model->where('ai_call_log.created_at >=', $filters['date_from'] . ' 00:00:00');
        }

        if ($filters['date_to'] !== '') {
            $model->where('ai_call_log.created_at <=', $filters['date_to'] . ' 23:59:59');
        }

        $perPage = (int) ($this->request->getGet('per_page') ?: 10);
        $perPage = in_array($perPage, [10, 25, 50], true) ? $perPage : 10;

        $entries = $model->orderBy('ai_call_log.created_at', 'desc')->paginate($perPage);

        return view('ai_call_log/index', [
            'pageTitle' => 'AI Call Log',
            'entries'   => $entries,
            'pager'     => $model->pager,
            'perPage'   => $perPage,
            'filters'   => $filters,
            'features'  => (new AiCallLogModel())->distinctFeatures(),
            'stats'     => [
                'total'   => (new AiCallLogModel())->countAllResults(),
                'success' => (new AiCallLogModel())->where('success', 1)->countAllResults(),
                'failed'  => (new AiCallLogModel())->where('success', 0)->countAllResults(),
                'tokens'  => (int) ((new AiCallLogModel())->selectSum('input_tokens')->first()->input_tokens ?? 0)
                             + (int) ((new AiCallLogModel())->selectSum('output_tokens')->first()->output_tokens ?? 0),
            ],
        ]);
    }
}
