'use strict';

var server = require('next/server');
var drizzleOrm = require('drizzle-orm');
var pgCore = require('drizzle-orm/pg-core');

// src/calendar/routes/index.ts
var userRole = pgCore.pgEnum("UserRole", ["USER", "ADMIN", "SUPER_ADMIN"]);
var user = pgCore.pgTable(
  "User",
  {
    id: pgCore.text().primaryKey().notNull(),
    email: pgCore.text().notNull(),
    emailVerified: pgCore.boolean().default(false).notNull(),
    username: pgCore.text().notNull(),
    password: pgCore.text(),
    name: pgCore.text(),
    nickname: pgCore.text(),
    image: pgCore.text(),
    avatar: pgCore.text(),
    role: userRole().default("USER").notNull(),
    preferences: pgCore.jsonb(),
    createdAt: pgCore.timestamp({ precision: 3, mode: "string" }).default(drizzleOrm.sql`CURRENT_TIMESTAMP`).notNull(),
    updatedAt: pgCore.timestamp({ precision: 3, mode: "string" }).notNull(),
    twoFactorEnabled: pgCore.boolean().default(false).notNull()
  },
  (table) => [
    pgCore.uniqueIndex("User_email_key").using("btree", table.email.asc().nullsLast().op("text_ops")),
    pgCore.uniqueIndex("User_username_key").using(
      "btree",
      table.username.asc().nullsLast().op("text_ops")
    )
  ]
);
var session = pgCore.pgTable(
  "Session",
  {
    id: pgCore.text().primaryKey().notNull(),
    userId: pgCore.text().notNull(),
    token: pgCore.text().notNull(),
    expiresAt: pgCore.timestamp({ precision: 3, mode: "string" }).notNull(),
    ipAddress: pgCore.text(),
    userAgent: pgCore.text(),
    createdAt: pgCore.timestamp({ precision: 3, mode: "string" }).default(drizzleOrm.sql`CURRENT_TIMESTAMP`).notNull(),
    updatedAt: pgCore.timestamp({ precision: 3, mode: "string" }).default(drizzleOrm.sql`CURRENT_TIMESTAMP`).notNull()
  },
  (table) => [
    pgCore.uniqueIndex("Session_token_key").using("btree", table.token.asc().nullsLast().op("text_ops")),
    pgCore.foreignKey({
      columns: [table.userId],
      foreignColumns: [user.id],
      name: "Session_userId_fkey"
    }).onUpdate("cascade").onDelete("cascade")
  ]
);
var account = pgCore.pgTable(
  "Account",
  {
    id: pgCore.text().primaryKey().notNull(),
    accountId: pgCore.text().notNull(),
    providerId: pgCore.text().notNull(),
    // 提供商: github, google, wechat 等
    userId: pgCore.text().notNull(),
    accessToken: pgCore.text(),
    refreshToken: pgCore.text(),
    idToken: pgCore.text(),
    accessTokenExpiresAt: pgCore.timestamp({ precision: 3, mode: "string" }),
    refreshTokenExpiresAt: pgCore.timestamp({ precision: 3, mode: "string" }),
    scope: pgCore.text(),
    password: pgCore.text(),
    createdAt: pgCore.timestamp({ precision: 3, mode: "string" }).default(drizzleOrm.sql`CURRENT_TIMESTAMP`).notNull(),
    updatedAt: pgCore.timestamp({ precision: 3, mode: "string" }).notNull()
  },
  (table) => [
    pgCore.uniqueIndex("Account_providerId_accountId_key").using(
      "btree",
      table.providerId.asc().nullsLast().op("text_ops"),
      table.accountId.asc().nullsLast().op("text_ops")
    ),
    pgCore.foreignKey({
      columns: [table.userId],
      foreignColumns: [user.id],
      name: "Account_userId_fkey"
    }).onUpdate("cascade").onDelete("cascade")
  ]
);
pgCore.pgTable(
  "verifications",
  {
    id: pgCore.text().primaryKey().notNull(),
    identifier: pgCore.text().notNull(),
    // 邮箱或手机号
    value: pgCore.text().notNull(),
    // 验证码
    expiresAt: pgCore.timestamp({ precision: 3, mode: "string" }).notNull(),
    createdAt: pgCore.timestamp({ precision: 3, mode: "string" }).default(drizzleOrm.sql`CURRENT_TIMESTAMP`).notNull()
  },
  (table) => [
    pgCore.uniqueIndex("verifications_identifier_value_key").using(
      "btree",
      table.identifier.asc().nullsLast().op("text_ops"),
      table.value.asc().nullsLast().op("text_ops")
    )
  ]
);
drizzleOrm.relations(user, ({ many }) => ({
  sessions: many(session),
  accounts: many(account)
}));
drizzleOrm.relations(session, ({ one }) => ({
  user: one(user, {
    fields: [session.userId],
    references: [user.id]
  })
}));
drizzleOrm.relations(account, ({ one }) => ({
  user: one(user, {
    fields: [account.userId],
    references: [user.id]
  })
}));

// src/calendar/db/schema.ts
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(() => 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(() => 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(() => user.id, { onDelete: "cascade" }),
  sharedByUserId: pgCore.integer("shared_by_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
  permission: pgCore.varchar("permission", { length: 20 }).notNull().default("read"),
  // read, write
  createdAt: pgCore.timestamp("created_at").defaultNow().notNull()
});
drizzleOrm.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)
}));
drizzleOrm.relations(recurrenceRules, ({ one }) => ({
  event: one(calendarEvents, {
    fields: [recurrenceRules.eventId],
    references: [calendarEvents.id]
  })
}));
drizzleOrm.relations(reminders, ({ one }) => ({
  event: one(calendarEvents, {
    fields: [reminders.eventId],
    references: [calendarEvents.id]
  })
}));
drizzleOrm.relations(calendarConfigs, ({ one }) => ({
  user: one(user, {
    fields: [calendarConfigs.userId],
    references: [user.id]
  })
}));
drizzleOrm.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]
  })
}));

// src/calendar/db/calendarDbService.ts
var CalendarDbService = class {
  /**
   * 设置数据库实例
   */
  setDb(db) {
    this._db = db;
  }
  /**
   * 数据库是否已初始化
   */
  isConfigured() {
    return Boolean(this._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();

// src/calendar/routes/index.ts
function initDbService(db) {
  if (db) {
    calendarDbService.setDb(db);
  }
}
function createGetEventsHandler(config) {
  initDbService(config.db);
  return async (request) => {
    try {
      const user2 = await config.validateAuth(request);
      if (!user2) {
        return server.NextResponse.json({ success: false, error: "\u672A\u6388\u6743\u8BBF\u95EE" }, { status: 401 });
      }
      const { searchParams } = new URL(request.url);
      const startDateStr = searchParams.get("startDate");
      const endDateStr = searchParams.get("endDate");
      let startDate;
      let endDate;
      if (startDateStr) {
        startDate = new Date(startDateStr);
        if (isNaN(startDate.getTime())) {
          return server.NextResponse.json({ success: false, error: "\u5F00\u59CB\u65E5\u671F\u683C\u5F0F\u65E0\u6548" }, { status: 400 });
        }
      }
      if (endDateStr) {
        endDate = new Date(endDateStr);
        if (isNaN(endDate.getTime())) {
          return server.NextResponse.json({ success: false, error: "\u7ED3\u675F\u65E5\u671F\u683C\u5F0F\u65E0\u6548" }, { status: 400 });
        }
      }
      const events = await calendarDbService.getAllEvents(user2.id, startDate, endDate);
      return server.NextResponse.json({
        success: true,
        data: events,
        message: "\u83B7\u53D6\u4E8B\u4EF6\u5217\u8868\u6210\u529F"
      });
    } catch (error) {
      console.error("\u83B7\u53D6\u4E8B\u4EF6\u5931\u8D25\uFF1A", error);
      return server.NextResponse.json({ success: false, error: "\u670D\u52A1\u5668\u5185\u90E8\u9519\u8BEF" }, { status: 500 });
    }
  };
}
function createCreateEventHandler(config) {
  initDbService(config.db);
  return async (request) => {
    try {
      const user2 = await config.validateAuth(request);
      if (!user2) {
        return server.NextResponse.json({ success: false, error: "\u672A\u6388\u6743\u8BBF\u95EE" }, { status: 401 });
      }
      const body = await request.json();
      if (!body.title || typeof body.title !== "string" || body.title.trim() === "") {
        return server.NextResponse.json({ success: false, error: "\u4E8B\u4EF6\u6807\u9898\u4E0D\u80FD\u4E3A\u7A7A" }, { status: 400 });
      }
      if (!body.startTime || !body.endTime) {
        return server.NextResponse.json({ success: false, error: "\u5F00\u59CB\u65F6\u95F4\u548C\u7ED3\u675F\u65F6\u95F4\u4E0D\u80FD\u4E3A\u7A7A" }, { status: 400 });
      }
      const startTime = new Date(body.startTime);
      const endTime = new Date(body.endTime);
      if (isNaN(startTime.getTime()) || isNaN(endTime.getTime())) {
        return server.NextResponse.json({ success: false, error: "\u65E5\u671F\u683C\u5F0F\u65E0\u6548" }, { status: 400 });
      }
      if (startTime.getTime() >= endTime.getTime()) {
        return server.NextResponse.json({ success: false, error: "\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4" }, { status: 400 });
      }
      const eventData = {
        title: body.title.trim(),
        description: body.description || null,
        startTime,
        endTime,
        allDay: Boolean(body.allDay),
        location: body.location || null,
        color: body.color || "#3B82F6",
        userId: user2.id
      };
      const newEvent = await calendarDbService.createEvent(eventData);
      if (body.recurrence) {
        await calendarDbService.createRecurrenceRule({
          eventId: newEvent.id,
          ...body.recurrence,
          endDate: body.recurrence.endDate ? new Date(body.recurrence.endDate) : void 0
        });
      }
      if (body.reminders && Array.isArray(body.reminders)) {
        for (const reminder of body.reminders) {
          if (reminder.reminderTime) {
            await calendarDbService.createReminder({
              eventId: newEvent.id,
              reminderTime: new Date(reminder.reminderTime),
              reminderType: reminder.reminderType || "notification",
              status: "pending"
            });
          }
        }
      }
      return server.NextResponse.json({
        success: true,
        data: newEvent,
        message: "\u521B\u5EFA\u4E8B\u4EF6\u6210\u529F"
      });
    } catch (error) {
      console.error("\u521B\u5EFA\u4E8B\u4EF6\u5931\u8D25\uFF1A", error);
      return server.NextResponse.json({ success: false, error: "\u670D\u52A1\u5668\u5185\u90E8\u9519\u8BEF" }, { status: 500 });
    }
  };
}
function createGetEventByIdHandler(config) {
  initDbService(config.db);
  return async (request, { params }) => {
    try {
      const user2 = await config.validateAuth(request);
      if (!user2) {
        return server.NextResponse.json({ success: false, error: "\u672A\u6388\u6743\u8BBF\u95EE" }, { status: 401 });
      }
      const eventId = parseInt(params.id);
      if (isNaN(eventId)) {
        return server.NextResponse.json({ success: false, error: "\u4E8B\u4EF6ID\u65E0\u6548" }, { status: 400 });
      }
      const event = await calendarDbService.getEventById(eventId);
      if (!event) {
        return server.NextResponse.json({ success: false, error: "\u4E8B\u4EF6\u4E0D\u5B58\u5728" }, { status: 404 });
      }
      if (event.userId !== user2.id) {
        return server.NextResponse.json({ success: false, error: "\u65E0\u6743\u8BBF\u95EE\u6B64\u4E8B\u4EF6" }, { status: 403 });
      }
      const [recurrenceRule, reminders2] = await Promise.all([
        calendarDbService.getRecurrenceRule(eventId),
        calendarDbService.getEventReminders(eventId)
      ]);
      return server.NextResponse.json({
        success: true,
        data: {
          ...event,
          recurrenceRule: recurrenceRule || void 0,
          reminders: reminders2 || []
        },
        message: "\u83B7\u53D6\u4E8B\u4EF6\u6210\u529F"
      });
    } catch (error) {
      console.error("\u83B7\u53D6\u4E8B\u4EF6\u5931\u8D25\uFF1A", error);
      return server.NextResponse.json({ success: false, error: "\u670D\u52A1\u5668\u5185\u90E8\u9519\u8BEF" }, { status: 500 });
    }
  };
}
function createUpdateEventHandler(config) {
  initDbService(config.db);
  return async (request, { params }) => {
    try {
      const user2 = await config.validateAuth(request);
      if (!user2) {
        return server.NextResponse.json({ success: false, error: "\u672A\u6388\u6743\u8BBF\u95EE" }, { status: 401 });
      }
      const eventId = parseInt(params.id);
      if (isNaN(eventId)) {
        return server.NextResponse.json({ success: false, error: "\u4E8B\u4EF6ID\u65E0\u6548" }, { status: 400 });
      }
      const existingEvent = await calendarDbService.getEventById(eventId);
      if (!existingEvent || existingEvent.userId !== user2.id) {
        return server.NextResponse.json({ success: false, error: "\u4E8B\u4EF6\u4E0D\u5B58\u5728\u6216\u65E0\u6743\u4FEE\u6539" }, { status: 404 });
      }
      const body = await request.json();
      const updateData = {};
      if (body.title !== void 0) updateData.title = body.title.trim();
      if (body.description !== void 0) updateData.description = body.description;
      if (body.startTime !== void 0) updateData.startTime = new Date(body.startTime);
      if (body.endTime !== void 0) updateData.endTime = new Date(body.endTime);
      if (body.allDay !== void 0) updateData.allDay = Boolean(body.allDay);
      if (body.location !== void 0) updateData.location = body.location;
      if (body.color !== void 0) updateData.color = body.color;
      const updatedEvent = await calendarDbService.updateEvent(eventId, updateData);
      if (body.recurrence !== void 0) {
        await calendarDbService.deleteRecurrenceRule(eventId);
        if (body.recurrence) {
          await calendarDbService.createRecurrenceRule({
            eventId,
            ...body.recurrence,
            endDate: body.recurrence.endDate ? new Date(body.recurrence.endDate) : void 0
          });
        }
      }
      if (body.reminders !== void 0) {
        await calendarDbService.deleteEventReminders(eventId);
        if (Array.isArray(body.reminders)) {
          for (const reminder of body.reminders) {
            if (reminder.reminderTime) {
              await calendarDbService.createReminder({
                eventId,
                reminderTime: new Date(reminder.reminderTime),
                reminderType: reminder.reminderType || "notification",
                status: "pending"
              });
            }
          }
        }
      }
      return server.NextResponse.json({
        success: true,
        data: updatedEvent,
        message: "\u66F4\u65B0\u4E8B\u4EF6\u6210\u529F"
      });
    } catch (error) {
      console.error("\u66F4\u65B0\u4E8B\u4EF6\u5931\u8D25\uFF1A", error);
      return server.NextResponse.json({ success: false, error: "\u670D\u52A1\u5668\u5185\u90E8\u9519\u8BEF" }, { status: 500 });
    }
  };
}
function createDeleteEventHandler(config) {
  initDbService(config.db);
  return async (request, { params }) => {
    try {
      const user2 = await config.validateAuth(request);
      if (!user2) {
        return server.NextResponse.json({ success: false, error: "\u672A\u6388\u6743\u8BBF\u95EE" }, { status: 401 });
      }
      const eventId = parseInt(params.id);
      if (isNaN(eventId)) {
        return server.NextResponse.json({ success: false, error: "\u4E8B\u4EF6ID\u65E0\u6548" }, { status: 400 });
      }
      const existingEvent = await calendarDbService.getEventById(eventId);
      if (!existingEvent || existingEvent.userId !== user2.id) {
        return server.NextResponse.json({ success: false, error: "\u4E8B\u4EF6\u4E0D\u5B58\u5728\u6216\u65E0\u6743\u5220\u9664" }, { status: 404 });
      }
      await calendarDbService.deleteEvent(eventId);
      return server.NextResponse.json({
        success: true,
        message: "\u5220\u9664\u4E8B\u4EF6\u6210\u529F"
      });
    } catch (error) {
      console.error("\u5220\u9664\u4E8B\u4EF6\u5931\u8D25\uFF1A", error);
      return server.NextResponse.json({ success: false, error: "\u670D\u52A1\u5668\u5185\u90E8\u9519\u8BEF" }, { status: 500 });
    }
  };
}
function createBatchDeleteEventsHandler(config) {
  initDbService(config.db);
  return async (request) => {
    try {
      const user2 = await config.validateAuth(request);
      if (!user2) {
        return server.NextResponse.json({ success: false, error: "\u672A\u6388\u6743\u8BBF\u95EE" }, { status: 401 });
      }
      const body = await request.json();
      if (!body.eventIds || !Array.isArray(body.eventIds)) {
        return server.NextResponse.json({ success: false, error: "\u4E8B\u4EF6ID\u5217\u8868\u4E0D\u80FD\u4E3A\u7A7A" }, { status: 400 });
      }
      const results = await Promise.all(
        body.eventIds.map(async (id) => {
          const event = await calendarDbService.getEventById(id);
          if (event && event.userId === user2.id) {
            await calendarDbService.deleteEvent(id);
            return true;
          }
          return false;
        })
      );
      const deletedCount = results.filter(Boolean).length;
      return server.NextResponse.json({
        success: true,
        data: { deletedCount },
        message: "\u6210\u529F\u5220\u9664 " + deletedCount + " \u4E2A\u4E8B\u4EF6"
      });
    } catch (error) {
      console.error("\u6279\u91CF\u5220\u9664\u4E8B\u4EF6\u5931\u8D25\uFF1A", error);
      return server.NextResponse.json({ success: false, error: "\u670D\u52A1\u5668\u5185\u90E8\u9519\u8BEF" }, { status: 500 });
    }
  };
}
function createConfigHandler(config) {
  initDbService(config.db);
  return {
    GET: async (request) => {
      try {
        const user2 = await config.validateAuth(request);
        if (!user2) {
          return server.NextResponse.json({ success: false, error: "\u672A\u6388\u6743\u8BBF\u95EE" }, { status: 401 });
        }
        const dbConfig = await calendarDbService.getUserConfig(user2.id);
        return server.NextResponse.json({
          success: true,
          data: dbConfig || {
            firstDayOfWeek: 1,
            workingHoursStart: "09:00",
            workingHoursEnd: "18:00",
            timeZone: "Asia/Shanghai",
            dateFormat: "YYYY-MM-DD",
            timeFormat: "HH:mm",
            defaultView: "month",
            defaultEventColor: "#3B82F6",
            weekends: true,
            eventColors: {}
          },
          message: "\u83B7\u53D6\u914D\u7F6E\u6210\u529F"
        });
      } catch (error) {
        console.error("\u83B7\u53D6\u914D\u7F6E\u5931\u8D25\uFF1A", error);
        return server.NextResponse.json({ success: false, error: "\u670D\u52A1\u5668\u5185\u90E8\u9519\u8BEF" }, { status: 500 });
      }
    },
    PUT: async (request) => {
      try {
        const user2 = await config.validateAuth(request);
        if (!user2) {
          return server.NextResponse.json({ success: false, error: "\u672A\u6388\u6743\u8BBF\u95EE" }, { status: 401 });
        }
        const body = await request.json();
        const updatedConfig = await calendarDbService.upsertUserConfig(user2.id, body);
        return server.NextResponse.json({
          success: true,
          data: updatedConfig,
          message: "\u66F4\u65B0\u914D\u7F6E\u6210\u529F"
        });
      } catch (error) {
        console.error("\u66F4\u65B0\u914D\u7F6E\u5931\u8D25\uFF1A", error);
        return server.NextResponse.json({ success: false, error: "\u670D\u52A1\u5668\u5185\u90E8\u9519\u8BEF" }, { status: 500 });
      }
    }
  };
}

exports.createBatchDeleteEventsHandler = createBatchDeleteEventsHandler;
exports.createConfigHandler = createConfigHandler;
exports.createCreateEventHandler = createCreateEventHandler;
exports.createDeleteEventHandler = createDeleteEventHandler;
exports.createGetEventByIdHandler = createGetEventByIdHandler;
exports.createGetEventsHandler = createGetEventsHandler;
exports.createUpdateEventHandler = createUpdateEventHandler;
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map