import { pgTable, text, boolean, timestamp, integer, jsonb } from "drizzle-orm/pg-core";
import { relations } from "drizzle-orm";
import { users } from "./users";

export const webhooks = pgTable("webhooks", {
  id: text("id").primaryKey(),
  userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
  url: text("url").notNull(),
  events: text("events").array().notNull().default([]),
  secret: text("secret").notNull(),
  active: boolean("active").notNull().default(true),
  createdAt: timestamp("created_at").notNull().defaultNow(),
});

export const webhookDeliveries = pgTable("webhook_deliveries", {
  id: text("id").primaryKey(),
  webhookId: text("webhook_id").notNull().references(() => webhooks.id, { onDelete: "cascade" }),
  event: text("event").notNull(),
  payload: jsonb("payload"),
  statusCode: integer("status_code"),
  success: boolean("success").notNull().default(false),
  attempts: integer("attempts").notNull().default(0),
  createdAt: timestamp("created_at").notNull().defaultNow(),
});

export const webhooksRelations = relations(webhooks, ({ one, many }) => ({
  user: one(users, { fields: [webhooks.userId], references: [users.id] }),
  deliveries: many(webhookDeliveries),
}));

export const webhookDeliveriesRelations = relations(webhookDeliveries, ({ one }) => ({
  webhook: one(webhooks, { fields: [webhookDeliveries.webhookId], references: [webhooks.id] }),
}));

// Site-wide ops webhooks (new signup, support ticket, report filed) — unlike
// `webhooks` above, these aren't owned by a single user; any admin can manage
// them and every active one fires regardless of who created it.
export const adminWebhooks = pgTable("admin_webhooks", {
  id: text("id").primaryKey(),
  createdById: text("created_by_id").references(() => users.id, { onDelete: "set null" }),
  url: text("url").notNull(),
  events: text("events").array().notNull().default([]),
  secret: text("secret").notNull(),
  active: boolean("active").notNull().default(true),
  createdAt: timestamp("created_at").notNull().defaultNow(),
});

export const adminWebhookDeliveries = pgTable("admin_webhook_deliveries", {
  id: text("id").primaryKey(),
  webhookId: text("webhook_id").notNull().references(() => adminWebhooks.id, { onDelete: "cascade" }),
  event: text("event").notNull(),
  payload: jsonb("payload"),
  statusCode: integer("status_code"),
  success: boolean("success").notNull().default(false),
  attempts: integer("attempts").notNull().default(0),
  createdAt: timestamp("created_at").notNull().defaultNow(),
});

export const adminWebhooksRelations = relations(adminWebhooks, ({ one, many }) => ({
  createdBy: one(users, { fields: [adminWebhooks.createdById], references: [users.id] }),
  deliveries: many(adminWebhookDeliveries),
}));

export const adminWebhookDeliveriesRelations = relations(adminWebhookDeliveries, ({ one }) => ({
  webhook: one(adminWebhooks, { fields: [adminWebhookDeliveries.webhookId], references: [adminWebhooks.id] }),
}));
