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

import { tenants } from "./tenants"
import { helpdesk_contacts } from "./helpdesk_contacts"
import { contacts } from "./contacts"
import { customers } from "./customers"
import { authUsers } from "./auth_users"
import { helpdesk_channel_instances } from "./helpdesk_channel_instances"

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

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

    channelInstanceId: uuid("channel_instance_id")
        .notNull()
        .references(() => helpdesk_channel_instances.id, { onDelete: "cascade" }),

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

    subject: text("subject"),

    status: text("status").notNull().default("open"),

    priority: text("priority").default("normal"),

    assigneeUserId: uuid("assignee_user_id").references(() => authUsers.id),

    lastMessageAt: timestamp("last_message_at", { withTimezone: true }),

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

    customerId: bigint("customer_id", { mode: "number" }).references(
        () => customers.id,
        { onDelete: "set null" }
    ),

    contactPersonId: bigint("contact_person_id", { mode: "number" }).references(
        () => contacts.id,
        { onDelete: "set null" }
    ),

    ticketNumber: text("ticket_number"),
})

export type HelpdeskConversation =
    typeof helpdesk_conversations.$inferSelect
export type NewHelpdeskConversation =
    typeof helpdesk_conversations.$inferInsert
