<?php

namespace App\Models;

/** See CreateConciergeTables's migration comment. */
class ConciergeMessageModel extends TenantModel
{
    protected $table            = 'concierge_messages';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';
    protected $updatedField     = '';

    protected $allowedFields = [
        'conversation_id',
        'direction',
        'status',
        'body',
        'whatsapp_message_id',
    ];

    public function forConversation(int $conversationId): array
    {
        return $this->where('conversation_id', $conversationId)->orderBy('id', 'asc')->findAll();
    }

    public function alreadyReceived(string $whatsappMessageId): bool
    {
        return $this->where('whatsapp_message_id', $whatsappMessageId)->countAllResults() > 0;
    }

    /**
     * Recent turns for this conversation as Claude message-array shape,
     * oldest first, capped so a long-running thread doesn't grow the
     * prompt unboundedly. Only real inbound/sent-outbound turns count as
     * conversation history — a still-pending draft awaiting staff
     * approval isn't something the guest has seen yet, so it's excluded.
     */
    public function recentAsMessages(int $conversationId, int $limit = 20): array
    {
        $rows = $this->where('conversation_id', $conversationId)
            ->where('status !=', 'pending')
            ->orderBy('id', 'desc')
            ->limit($limit)
            ->findAll();

        $rows = array_reverse($rows);

        return array_map(
            static fn ($row) => ['role' => $row->direction === 'inbound' ? 'user' : 'assistant', 'content' => $row->body],
            $rows,
        );
    }
}
