<?php
require_once __DIR__ . '/../Core.php';

class ConversationState extends Model
{
    public function findByKey(string $conversationKey): ?array
    {
        $stmt = $this->db->prepare('SELECT cs.*, u.name AS assigned_user_name FROM conversation_states cs LEFT JOIN users u ON u.id = cs.assigned_user_id WHERE cs.conversation_key = ? LIMIT 1');
        $stmt->execute([$conversationKey]);
        return $stmt->fetch() ?: null;
    }

    public function save(array $data): void
    {
        $stmt = $this->db->prepare('INSERT INTO conversation_states (conversation_key, status, assigned_user_id, internal_note) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE status = VALUES(status), assigned_user_id = VALUES(assigned_user_id), internal_note = VALUES(internal_note), updated_at = CURRENT_TIMESTAMP');
        $stmt->execute([
            $data['conversation_key'],
            $data['status'] ?? 'open',
            (int)($data['assigned_user_id'] ?? 0) ?: null,
            trim((string)($data['internal_note'] ?? '')) ?: null,
        ]);
    }
}
