// modules/helpdesk/helpdesk.contact.service.ts
import { FastifyInstance } from 'fastify'
import { and, eq, or } from "drizzle-orm";
import { helpdesk_contacts } from "../../../db/schema";

export async function getOrCreateContact(
    server: FastifyInstance,
    tenant_id: number,
    { email, phone, display_name, customer_id, contact_id }: { email?: string; phone?: string; display_name?: string; customer_id?: number; contact_id?: number }
) {
    if (!email && !phone) throw new Error('Contact must have at least an email or phone')

    // Bestehenden Kontakt prüfen
    const matchConditions = []
    if (email) matchConditions.push(eq(helpdesk_contacts.email, email))
    if (phone) matchConditions.push(eq(helpdesk_contacts.phone, phone))

    const existing = await server.db
        .select()
        .from(helpdesk_contacts)
        .where(
            and(
                eq(helpdesk_contacts.tenantId, tenant_id),
                or(...matchConditions)
            )
        )
        .limit(1)

    if (existing[0]) return existing[0]

    // Anlegen
    const created = await server.db
        .insert(helpdesk_contacts)
        .values({
            tenantId: tenant_id,
            email,
            phone,
            displayName: display_name,
            customerId: customer_id,
            contactId: contact_id
        })
        .returning()

    return created[0]
}
