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

// Dedup log for inbound Stripe webhook events. Stripe may redeliver the same
// event within its retry/tolerance window; we insert the event id here
// before processing and skip processing entirely if the insert hits the
// primary key conflict (i.e. we've already handled this event).
export const processedStripeEvents = pgTable("processed_stripe_events", {
  id: text("id").primaryKey(), // Stripe event id, e.g. "evt_..."
  type: text("type").notNull(),
  createdAt: timestamp("created_at").notNull().defaultNow(),
});

// Billing/invoice details, separate from the display `name` on `users` —
// fullName here is the legal/billing name used on invoices. All columns are
// nullable at the DB level (existing users have none of this filled in yet);
// fullName being "mandatory" is enforced by the API/form, not a NOT NULL
// constraint, since we can't backfill it for every existing user.
export const userBillingDetails = pgTable("user_billing_details", {
  id: text("id").primaryKey(),
  userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }).unique(),
  fullName: text("full_name"),
  addressLine1: text("address_line1"),
  addressLine2: text("address_line2"),
  city: text("city"),
  postalCode: text("postal_code"),
  country: text("country"),
  phone: text("phone"),
  updatedAt: timestamp("updated_at").notNull().defaultNow(),
});

export const userBillingDetailsRelations = relations(userBillingDetails, ({ one }) => ({
  user: one(users, { fields: [userBillingDetails.userId], references: [users.id] }),
}));
