<?php

declare(strict_types=1);

namespace App\Models;

use CodeIgniter\Model;

class ChatHistoryModel extends Model
{
    protected $table            = 'chat_history';
    protected $primaryKey       = 'id';
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $allowedFields    = [
        'user_id',
        'document_id',
        'message_role',
        'message_text',
    ];
    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';
    protected $updatedField     = 'updated_at';
    protected $deletedField     = 'deleted_at';
    protected $validationRules  = [];
    protected $validationMessages = [];
    protected $skipValidation     = false;

    public function getByUserAndDocument(int $userId, ?int $docId = null): array
    {
        $builder = $this->builder();
        $builder->where('user_id', $userId);

        if ($docId !== null) {
            $builder->where('document_id', $docId);
        }

        $builder->orderBy('created_at', 'ASC');
        return $builder->get()->getResultArray();
    }
}
