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

import { tenants } from "./tenants"
import { authUsers } from "./auth_users"
import { telephonyExtensions } from "./telephony_extensions"

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

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

        provider: text("provider").notNull().default("telekom"),
        enabled: boolean("enabled").notNull().default(false),
        registrar: text("registrar").notNull().default("tel.t-online.de"),

        sipUser: text("sip_user"),
        authUser: text("auth_user"),
        password: text("password"),
        callerId: text("caller_id"),
        inboundExtension: text("inbound_extension").notNull().default("1001"),
        defaultRouteExtensionId: uuid("default_route_extension_id").references(() => telephonyExtensions.id, { onDelete: "set null" }),
        outboundPrefix: text("outbound_prefix").notNull().default("0"),
        externalSignalingAddress: text("external_signaling_address"),
        externalMediaAddress: text("external_media_address"),
        localNetworks: text("local_networks"),

        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) => ({
        tenantProviderIdx: uniqueIndex("telephony_trunks_tenant_provider_idx")
            .on(table.tenantId, table.provider),
    })
)

export type TelephonyTrunk = typeof telephonyTrunks.$inferSelect
export type NewTelephonyTrunk = typeof telephonyTrunks.$inferInsert
