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

import { tenants } from "./tenants"
import { authUsers } from "./auth_users"
import { teams } from "./teams"
import { branches } from "./branches"

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

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

        targetType: text("target_type").notNull(),
        targetUserId: uuid("target_user_id").references(() => authUsers.id, { onDelete: "cascade" }),
        targetTeamId: bigint("target_team_id", { mode: "number" }).references(() => teams.id, { onDelete: "cascade" }),
        targetBranchId: bigint("target_branch_id", { mode: "number" }).references(() => branches.id, { onDelete: "cascade" }),

        extension: text("extension").notNull(),
        displayName: text("display_name"),
        sipUsername: text("sip_username"),
        sipPassword: text("sip_password"),
        enabled: boolean("enabled").notNull().default(true),

        createdAt: timestamp("created_at", { withTimezone: true })
            .notNull()
            .defaultNow(),
        updatedAt: timestamp("updated_at", { withTimezone: true }),
        createdBy: uuid("created_by").references(() => authUsers.id),
        updatedBy: uuid("updated_by").references(() => authUsers.id),
    },
    (table) => ({
        tenantExtensionIdx: uniqueIndex("telephony_extensions_tenant_extension_idx")
            .on(table.tenantId, table.extension),
        tenantTargetIdx: index("telephony_extensions_tenant_target_idx")
            .on(table.tenantId, table.targetType),
    })
)

export type TelephonyExtension = typeof telephonyExtensions.$inferSelect
export type NewTelephonyExtension = typeof telephonyExtensions.$inferInsert
