'use strict';

var chunkSVWQN2LR_js = require('./chunk-SVWQN2LR.js');
var pgCore = require('drizzle-orm/pg-core');
var drizzleOrm = require('drizzle-orm');

var calendarEvents = pgCore.pgTable("calendar_events", {
  id: pgCore.serial("id").primaryKey(),
  title: pgCore.varchar("title", { length: 255 }).notNull(),
  description: pgCore.text("description"),
  startTime: pgCore.timestamp("start_time").notNull(),
  endTime: pgCore.timestamp("end_time").notNull(),
  allDay: pgCore.boolean("all_day").notNull().default(false),
  location: pgCore.varchar("location", { length: 500 }),
  color: pgCore.varchar("color", { length: 7 }).notNull().default("#3B82F6"),
  // 十六进制颜色值
  priority: pgCore.varchar("priority", { length: 10 }).notNull().default("normal"),
  // low, normal, high, urgent
  userId: pgCore.integer("user_id").notNull().references(() => chunkSVWQN2LR_js.user.id, { onDelete: "cascade" }),
  createdAt: pgCore.timestamp("created_at").defaultNow().notNull(),
  updatedAt: pgCore.timestamp("updated_at").defaultNow().notNull()
});
var recurrenceRules = pgCore.pgTable("recurrence_rules", {
  id: pgCore.serial("id").primaryKey(),
  eventId: pgCore.integer("event_id").notNull().references(() => calendarEvents.id, { onDelete: "cascade" }),
  ruleType: pgCore.varchar("rule_type", { length: 20 }).notNull(),
  // daily, weekly, monthly, yearly, custom
  interval: pgCore.integer("interval").notNull().default(1),
  // 间隔
  endDate: pgCore.timestamp("end_date"),
  // 结束日期
  count: pgCore.integer("count"),
  // 重复次数
  byWeekday: pgCore.json("by_weekday").$type(),
  // 周几重复 [0,1,2,3,4,5,6]，0=周日
  byMonthday: pgCore.json("by_monthday").$type(),
  // 月中的第几天 [1,2,...,31]
  byMonth: pgCore.json("by_month").$type(),
  // 第几月 [1,2,...,12]
  createdAt: pgCore.timestamp("created_at").defaultNow().notNull()
});
var reminders = pgCore.pgTable("reminders", {
  id: pgCore.serial("id").primaryKey(),
  eventId: pgCore.integer("event_id").notNull().references(() => calendarEvents.id, { onDelete: "cascade" }),
  reminderTime: pgCore.timestamp("reminder_time").notNull(),
  // 提醒时间
  reminderType: pgCore.varchar("reminder_type", { length: 20 }).notNull(),
  // notification, email, sms
  status: pgCore.varchar("status", { length: 20 }).notNull().default("pending"),
  // pending, sent, failed
  createdAt: pgCore.timestamp("created_at").defaultNow().notNull(),
  updatedAt: pgCore.timestamp("updated_at").defaultNow().notNull()
});
var calendarConfigs = pgCore.pgTable("calendar_configs", {
  id: pgCore.serial("id").primaryKey(),
  userId: pgCore.integer("user_id").notNull().references(() => chunkSVWQN2LR_js.user.id, { onDelete: "cascade" }).unique(),
  firstDayOfWeek: pgCore.integer("first_day_of_week").notNull().default(1),
  // 0=周日, 1=周一
  workingHoursStart: pgCore.varchar("working_hours_start", { length: 5 }).notNull().default("09:00"),
  workingHoursEnd: pgCore.varchar("working_hours_end", { length: 5 }).notNull().default("18:00"),
  timeZone: pgCore.varchar("time_zone", { length: 50 }).notNull().default("Asia/Shanghai"),
  dateFormat: pgCore.varchar("date_format", { length: 20 }).notNull().default("YYYY-MM-DD"),
  timeFormat: pgCore.varchar("time_format", { length: 20 }).notNull().default("HH:mm"),
  defaultView: pgCore.varchar("default_view", { length: 20 }).notNull().default("month"),
  // month, week, day, agenda
  defaultEventColor: pgCore.varchar("default_event_color", { length: 7 }).notNull().default("#3B82F6"),
  weekends: pgCore.boolean("weekends").notNull().default(true),
  eventColors: pgCore.json("event_colors").$type().default({
    blue: "#3B82F6",
    green: "#10B981",
    purple: "#8B5CF6",
    red: "#EF4444",
    yellow: "#F59E0B",
    pink: "#EC4899",
    indigo: "#6366F1",
    gray: "#6B7280"
  }),
  createdAt: pgCore.timestamp("created_at").defaultNow().notNull(),
  updatedAt: pgCore.timestamp("updated_at").defaultNow().notNull()
});
var eventShares = pgCore.pgTable("event_shares", {
  id: pgCore.serial("id").primaryKey(),
  eventId: pgCore.integer("event_id").notNull().references(() => calendarEvents.id, { onDelete: "cascade" }),
  sharedWithUserId: pgCore.integer("shared_with_user_id").notNull().references(() => chunkSVWQN2LR_js.user.id, { onDelete: "cascade" }),
  sharedByUserId: pgCore.integer("shared_by_user_id").notNull().references(() => chunkSVWQN2LR_js.user.id, { onDelete: "cascade" }),
  permission: pgCore.varchar("permission", { length: 20 }).notNull().default("read"),
  // read, write
  createdAt: pgCore.timestamp("created_at").defaultNow().notNull()
});
var calendarEventsRelations = drizzleOrm.relations(calendarEvents, ({ one, many }) => ({
  user: one(chunkSVWQN2LR_js.user, {
    fields: [calendarEvents.userId],
    references: [chunkSVWQN2LR_js.user.id]
  }),
  recurrenceRule: one(recurrenceRules, {
    fields: [calendarEvents.id],
    references: [recurrenceRules.eventId]
  }),
  reminders: many(reminders),
  shares: many(eventShares)
}));
var recurrenceRulesRelations = drizzleOrm.relations(recurrenceRules, ({ one }) => ({
  event: one(calendarEvents, {
    fields: [recurrenceRules.eventId],
    references: [calendarEvents.id]
  })
}));
var remindersRelations = drizzleOrm.relations(reminders, ({ one }) => ({
  event: one(calendarEvents, {
    fields: [reminders.eventId],
    references: [calendarEvents.id]
  })
}));
var calendarConfigsRelations = drizzleOrm.relations(calendarConfigs, ({ one }) => ({
  user: one(chunkSVWQN2LR_js.user, {
    fields: [calendarConfigs.userId],
    references: [chunkSVWQN2LR_js.user.id]
  })
}));
var eventSharesRelations = drizzleOrm.relations(eventShares, ({ one }) => ({
  event: one(calendarEvents, {
    fields: [eventShares.eventId],
    references: [calendarEvents.id]
  }),
  sharedWithUser: one(chunkSVWQN2LR_js.user, {
    fields: [eventShares.sharedWithUserId],
    references: [chunkSVWQN2LR_js.user.id]
  }),
  sharedByUser: one(chunkSVWQN2LR_js.user, {
    fields: [eventShares.sharedByUserId],
    references: [chunkSVWQN2LR_js.user.id]
  })
}));
var CalendarDbService = class {
  /**
   * 设置数据库实例
   */
  setDb(db) {
    this._db = db;
  }
  /**
   * 获取数据库实例
   */
  get db() {
    if (!this._db) {
      throw new Error("CalendarDbService: Database instance not set. Call setDb() first.");
    }
    return this._db;
  }
  // ===== 事件基础操作 =====
  /**
   * 获取用户的所有事件（基础版本）
   */
  async getAllEvents(userId, startDate, endDate) {
    const conditions = [drizzleOrm.eq(calendarEvents.userId, userId)];
    if (startDate) {
      conditions.push(drizzleOrm.gte(calendarEvents.startTime, startDate));
    }
    if (endDate) {
      conditions.push(drizzleOrm.lte(calendarEvents.endTime, endDate));
    }
    const events = await this.db.select().from(calendarEvents).where(drizzleOrm.and(...conditions)).orderBy(drizzleOrm.asc(calendarEvents.startTime));
    return events;
  }
  /**
   * 根据ID获取事件
   */
  async getEventById(eventId) {
    const [event] = await this.db.select().from(calendarEvents).where(drizzleOrm.eq(calendarEvents.id, eventId)).limit(1);
    return event || null;
  }
  /**
   * 创建事件（基础版本）
   */
  async createEvent(eventData) {
    const [newEvent] = await this.db.insert(calendarEvents).values(eventData).returning();
    return newEvent;
  }
  /**
   * 更新事件
   */
  async updateEvent(eventId, eventData) {
    const updateData = {
      ...eventData,
      updatedAt: /* @__PURE__ */ new Date()
    };
    const [updatedEvent] = await this.db.update(calendarEvents).set(updateData).where(drizzleOrm.eq(calendarEvents.id, eventId)).returning();
    return updatedEvent;
  }
  /**
   * 删除事件
   */
  async deleteEvent(eventId) {
    await this.db.delete(calendarEvents).where(drizzleOrm.eq(calendarEvents.id, eventId));
  }
  // ===== 用户配置操作 =====
  /**
   * 获取用户的日历配置
   */
  async getUserConfig(userId) {
    const [config] = await this.db.select().from(calendarConfigs).where(drizzleOrm.eq(calendarConfigs.userId, userId)).limit(1);
    return config || null;
  }
  /**
   * 创建或更新用户配置
   */
  async upsertUserConfig(userId, configData) {
    const existingConfig = await this.getUserConfig(userId);
    if (existingConfig) {
      const [updatedConfig] = await this.db.update(calendarConfigs).set({
        ...configData,
        updatedAt: /* @__PURE__ */ new Date()
      }).where(drizzleOrm.eq(calendarConfigs.userId, userId)).returning();
      return updatedConfig;
    } else {
      const [newConfig] = await this.db.insert(calendarConfigs).values({
        userId,
        ...configData
      }).returning();
      return newConfig;
    }
  }
  /**
   * 为事件创建重复规则
   */
  async createRecurrenceRule(ruleData) {
    const [newRule] = await this.db.insert(recurrenceRules).values(ruleData).returning();
    return newRule;
  }
  /**
   * 获取事件的重复规则
   */
  async getRecurrenceRule(eventId) {
    const [rule] = await this.db.select().from(recurrenceRules).where(drizzleOrm.eq(recurrenceRules.eventId, eventId)).limit(1);
    return rule || null;
  }
  /**
   * 删除重复规则
   */
  async deleteRecurrenceRule(eventId) {
    await this.db.delete(recurrenceRules).where(drizzleOrm.eq(recurrenceRules.eventId, eventId));
  }
  /**
   * 为事件创建提醒
   */
  async createReminder(reminderData) {
    const [newReminder] = await this.db.insert(reminders).values({
      ...reminderData,
      status: reminderData.status || "pending"
    }).returning();
    return newReminder;
  }
  /**
   * 获取事件的提醒列表
   */
  async getEventReminders(eventId) {
    const remindersList = await this.db.select().from(reminders).where(drizzleOrm.eq(reminders.eventId, eventId)).orderBy(drizzleOrm.asc(reminders.reminderTime));
    return remindersList;
  }
  /**
   * 删除事件的所有提醒
   */
  async deleteEventReminders(eventId) {
    await this.db.delete(reminders).where(drizzleOrm.eq(reminders.eventId, eventId));
  }
  /**
   * 获取用户在指定时间范围内的事件数量
   */
  async getEventCount(userId, startDate, endDate) {
    const conditions = [drizzleOrm.eq(calendarEvents.userId, userId)];
    if (startDate) {
      conditions.push(drizzleOrm.gte(calendarEvents.startTime, startDate));
    }
    if (endDate) {
      conditions.push(drizzleOrm.lte(calendarEvents.endTime, endDate));
    }
    const result = await this.db.select({ count: calendarEvents.id }).from(calendarEvents).where(drizzleOrm.and(...conditions));
    return result.length;
  }
  /**
   * 搜索事件
   */
  async searchEvents(userId, searchTerm) {
    const events = await this.db.select().from(calendarEvents).where(
      drizzleOrm.and(
        drizzleOrm.eq(calendarEvents.userId, userId)
      )
    ).orderBy(drizzleOrm.desc(calendarEvents.startTime));
    return events.filter(
      (event) => event.title.toLowerCase().includes(searchTerm.toLowerCase()) || event.description && event.description.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }
  /**
   * 批量删除用户的所有事件
   */
  async deleteAllUserEvents(userId) {
    await this.db.delete(calendarEvents).where(drizzleOrm.eq(calendarEvents.userId, userId));
  }
};
var calendarDbService = new CalendarDbService();

exports.calendarConfigs = calendarConfigs;
exports.calendarConfigsRelations = calendarConfigsRelations;
exports.calendarDbService = calendarDbService;
exports.calendarEvents = calendarEvents;
exports.calendarEventsRelations = calendarEventsRelations;
exports.eventShares = eventShares;
exports.eventSharesRelations = eventSharesRelations;
exports.recurrenceRules = recurrenceRules;
exports.recurrenceRulesRelations = recurrenceRulesRelations;
exports.reminders = reminders;
exports.remindersRelations = remindersRelations;
//# sourceMappingURL=chunk-WC5QFO3T.js.map
//# sourceMappingURL=chunk-WC5QFO3T.js.map