import { user } from './chunk-AIKEVVDR.mjs';
import { pgTable, timestamp, integer, varchar, boolean, text, serial, json } from 'drizzle-orm/pg-core';
import { relations, eq, gte, lte, and, asc, desc } from 'drizzle-orm';

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

export { calendarConfigs, calendarConfigsRelations, calendarDbService, calendarEvents, calendarEventsRelations, eventShares, eventSharesRelations, recurrenceRules, recurrenceRulesRelations, reminders, remindersRelations };
//# sourceMappingURL=chunk-GVVS4IMM.mjs.map
//# sourceMappingURL=chunk-GVVS4IMM.mjs.map