<?php

namespace App\Models;

use CodeIgniter\Model;

class MessageModel extends Model
{
    protected $table         = 'messages';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $useSoftDeletes = true;
    protected $dateFormat    = 'datetime';
    protected $deletedField  = 'deleted_at';

    protected $allowedFields = [
        'conversation_id', 'sender_id', 'body',
    ];

    protected $validationRules = [
        'conversation_id' => 'required|is_natural_no_zero',
        'sender_id'       => 'required|is_natural_no_zero',
        'body'            => 'required|min_length[1]|max_length[5000]',
    ];

    /**
     * @return list<array<string, mixed>>
     */
    public function getForConversation(int $conversationId, ?int $afterId = null, int $limit = 100): array
    {
        $builder = $this->select('messages.*, users.first_name, users.last_name, users.username')
            ->join('users', 'users.id = messages.sender_id', 'left')
            ->where('messages.conversation_id', $conversationId)
            ->where('messages.deleted_at', null);

        if ($afterId) {
            $builder->where('messages.id >', $afterId);
        }

        return $builder->orderBy('messages.id', 'ASC')
            ->findAll($limit);
    }
}
