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

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

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

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

    updatedAt: timestamp("updated_at", { withTimezone: true })
        .notNull()
        .defaultNow(),

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

    userId: uuid("user_id")
        .notNull()
        .references(() => authUsers.id, { onDelete: "cascade", onUpdate: "cascade" }),

    createdBy: uuid("created_by").references(() => authUsers.id, {
        onDelete: "set null",
        onUpdate: "cascade",
    }),

    name: text("name").notNull(),
    keyPrefix: text("key_prefix").notNull(),
    keyHash: text("key_hash").notNull().unique(),

    active: boolean("active").notNull().default(true),

    lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
    expiresAt: timestamp("expires_at", { withTimezone: true }),
})

export type M2mApiKey = typeof m2mApiKeys.$inferSelect
export type NewM2mApiKey = typeof m2mApiKeys.$inferInsert
