import {
    pgTable,
    uuid,
    timestamp,
    text,
    jsonb,
    bigint,
} from "drizzle-orm/pg-core"

import { tenants } from "./tenants"
import { helpdesk_contacts } from "./helpdesk_contacts"
import { helpdesk_conversations } from "./helpdesk_conversations"
import { authUsers } from "./auth_users"

export const helpdesk_messages = pgTable("helpdesk_messages", {
    id: uuid("id").primaryKey().defaultRandom(),

    tenantId: bigint("tenant_id", { mode: "number" })
        .notNull()
        .references(() => tenants.id, { onDelete: "cascade" }),

    conversationId: uuid("conversation_id")
        .notNull()
        .references(() => helpdesk_conversations.id, { onDelete: "cascade" }),

    direction: text("direction").notNull(),

    authorUserId: uuid("author_user_id").references(() => authUsers.id),

    payload: jsonb("payload").notNull(),

    rawMeta: jsonb("raw_meta"),

    createdAt: timestamp("created_at", { withTimezone: true }).defaultNow(),

    contactId: uuid("contact_id").references(() => helpdesk_contacts.id, {
        onDelete: "set null",
    }),

    externalMessageId: text("external_message_id").unique(),

    receivedAt: timestamp("received_at", { withTimezone: true }).defaultNow(),
})

export type HelpdeskMessage = typeof helpdesk_messages.$inferSelect
export type NewHelpdeskMessage = typeof helpdesk_messages.$inferInsert
