// modules/helpdesk/helpdesk.message.service.ts
import { FastifyInstance } from 'fastify'
import { asc, eq } from "drizzle-orm";
import { helpdesk_conversations, helpdesk_messages } from "../../../db/schema";

export async function addMessage(
    server: FastifyInstance,
    {
        tenant_id,
        conversation_id,
        author_user_id = null,
        direction = 'incoming',
        payload,
        raw_meta = null,
        external_message_id = null,
    }: {
        tenant_id: number
        conversation_id: string
        author_user_id?: string | null
        direction?: 'incoming' | 'outgoing' | 'internal' | 'system'
        payload: any
        raw_meta?: any
        external_message_id?: string
    }
) {
    if (!payload?.text) throw new Error('Message payload requires text content')

    const inserted = await server.db
        .insert(helpdesk_messages)
        .values({
            tenantId: tenant_id,
            conversationId: conversation_id,
            authorUserId: author_user_id,
            direction,
            payload,
            rawMeta: raw_meta,
            externalMessageId: external_message_id,
            receivedAt: new Date(),
        })
        .returning()

    const message = inserted[0]

    // Letzte Nachricht aktualisieren
    await server.db
        .update(helpdesk_conversations)
        .set({ lastMessageAt: new Date() })
        .where(eq(helpdesk_conversations.id, conversation_id))

    return {
        ...message,
        author_user_id: message.authorUserId,
        conversation_id: message.conversationId,
        created_at: message.createdAt,
        external_message_id: message.externalMessageId,
        raw_meta: message.rawMeta,
        tenant_id: message.tenantId,
    }
}

export async function getMessages(server: FastifyInstance, conversation_id: string) {
    const data = await server.db
        .select()
        .from(helpdesk_messages)
        .where(eq(helpdesk_messages.conversationId, conversation_id))
        .orderBy(asc(helpdesk_messages.createdAt))

    return data.map((message) => ({
        ...message,
        author_user_id: message.authorUserId,
        conversation_id: message.conversationId,
        created_at: message.createdAt,
        external_message_id: message.externalMessageId,
        raw_meta: message.rawMeta,
        tenant_id: message.tenantId,
    }))
}
