// modules/helpdesk/helpdesk.inbound.routes.ts
import { FastifyPluginAsync } from 'fastify'
import { createConversation } from '../modules/helpdesk/helpdesk.conversation.service.js'
import { addMessage } from '../modules/helpdesk/helpdesk.message.service.js'
import { getOrCreateContact } from '../modules/helpdesk/helpdesk.contact.service.js'
import { findCustomerOrContactByEmailOrDomain } from "../utils/helpers";
import { eq } from "drizzle-orm";
import { helpdesk_channel_instances } from "../../db/schema";

const helpdeskInboundRoutes: FastifyPluginAsync = async (server) => {
    // Öffentliche POST-Route
    server.post('/helpdesk/inbound/:public_token', async (req, res) => {
        const { public_token } = req.params as { public_token: string }
        const { email, phone, display_name, subject, message } = req.body as {
            email: string,
            phone: string,
            display_name: string
            subject: string
            message: string
        }

        if (!message) {
            return res.status(400).send({ error: 'Message content required' })
        }

        // 1️⃣ Kanalinstanz anhand des Tokens ermitteln
        const channels = await server.db
            .select()
            .from(helpdesk_channel_instances)
            .where(eq(helpdesk_channel_instances.publicToken, public_token))
            .limit(1)
        const channel = channels[0]

        if (!channel) {
            return res.status(404).send({ error: 'Invalid channel token' })
        }

        const tenant_id = channel.tenantId
        const channel_instance_id = channel.id

        // @ts-ignore
        const {customer, contact: contactPerson} = await findCustomerOrContactByEmailOrDomain(server,email, tenant_id )


        // 2️⃣ Kontakt finden oder anlegen
        const contact = await getOrCreateContact(server, tenant_id, {
            email,
            phone,
            display_name,
            customer_id: customer,
            contact_id: contactPerson,
        })

        // 3️⃣ Konversation erstellen
        const conversation = await createConversation(server, {
            tenant_id,
            contact,
            channel_instance_id,
            subject: subject ?? 'Kontaktformular Anfrage',
            customer_id: customer,
            contact_person_id: contactPerson
        })

        // 4️⃣ Erste Nachricht hinzufügen
        await addMessage(server, {
            tenant_id,
            conversation_id: conversation.id,
            direction: 'incoming',
            payload: { type: 'text', text: message },
            raw_meta: { source: 'contact_form' },
        })

        // (optional) Auto-Antwort oder Event hier ergänzen

        return res.status(201).send({
            success: true,
            conversation_id: conversation.id,
        })
    })
}

export default helpdeskInboundRoutes
