import { sql } from "drizzle-orm"; import { boolean, check, index, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core"; import { households, users } from "../_core/schema"; export const calendars = pgTable( "calendars", { id: uuid("id").primaryKey().defaultRandom(), householdId: uuid("household_id") .notNull() .references(() => households.id, { onDelete: "cascade" }), ownerId: uuid("owner_id") .notNull() .references(() => users.id, { onDelete: "cascade" }), name: text("name").notNull(), color: text("color"), visibility: text("visibility").notNull().default("household"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (t) => [ check("calendars_visibility_check", sql`${t.visibility} in ('private', 'household')`), index("calendars_household_idx").on(t.householdId), index("calendars_owner_idx").on(t.ownerId), ], ); export const calendarEvents = pgTable( "calendar_events", { id: uuid("id").primaryKey().defaultRandom(), calendarId: uuid("calendar_id") .notNull() .references(() => calendars.id, { onDelete: "cascade" }), title: text("title").notNull(), startAt: timestamp("start_at", { withTimezone: true }).notNull(), endAt: timestamp("end_at", { withTimezone: true }).notNull(), allDay: boolean("all_day").notNull().default(false), location: text("location"), notes: text("notes"), ownerId: uuid("owner_id") .notNull() .references(() => users.id, { onDelete: "cascade" }), rrule: text("rrule"), externalSource: text("external_source"), externalId: text("external_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (t) => [ index("calendar_events_calendar_start_idx").on(t.calendarId, t.startAt), check("calendar_events_range_check", sql`${t.endAt} >= ${t.startAt}`), ], ); export type Calendar = typeof calendars.$inferSelect; export type CalendarEvent = typeof calendarEvents.$inferSelect;