import { calendarDbService } from '../../chunk-OCIJT5VO.mjs';
import '../../chunk-AIKEVVDR.mjs';
import '../../chunk-BJTO5JO5.mjs';
import { NextResponse } from 'next/server';

function initDbService(db) {
  if (db) {
    calendarDbService.setDb(db);
  }
}
function createGetEventsHandler(config) {
  initDbService(config.db);
  return async (request) => {
    try {
      const user = await config.validateAuth(request);
      if (!user) {
        return 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 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 NextResponse.json({ success: false, error: "\u7ED3\u675F\u65E5\u671F\u683C\u5F0F\u65E0\u6548" }, { status: 400 });
        }
      }
      const events = await calendarDbService.getAllEvents(user.id, startDate, endDate);
      return 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 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 user = await config.validateAuth(request);
      if (!user) {
        return 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 NextResponse.json({ success: false, error: "\u4E8B\u4EF6\u6807\u9898\u4E0D\u80FD\u4E3A\u7A7A" }, { status: 400 });
      }
      if (!body.startTime || !body.endTime) {
        return 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 NextResponse.json({ success: false, error: "\u65E5\u671F\u683C\u5F0F\u65E0\u6548" }, { status: 400 });
      }
      if (startTime.getTime() >= endTime.getTime()) {
        return 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: user.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 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 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 user = await config.validateAuth(request);
      if (!user) {
        return NextResponse.json({ success: false, error: "\u672A\u6388\u6743\u8BBF\u95EE" }, { status: 401 });
      }
      const eventId = parseInt(params.id);
      if (isNaN(eventId)) {
        return NextResponse.json({ success: false, error: "\u4E8B\u4EF6ID\u65E0\u6548" }, { status: 400 });
      }
      const event = await calendarDbService.getEventById(eventId);
      if (!event) {
        return NextResponse.json({ success: false, error: "\u4E8B\u4EF6\u4E0D\u5B58\u5728" }, { status: 404 });
      }
      if (event.userId !== user.id) {
        return NextResponse.json({ success: false, error: "\u65E0\u6743\u8BBF\u95EE\u6B64\u4E8B\u4EF6" }, { status: 403 });
      }
      const [recurrenceRule, reminders] = await Promise.all([
        calendarDbService.getRecurrenceRule(eventId),
        calendarDbService.getEventReminders(eventId)
      ]);
      return NextResponse.json({
        success: true,
        data: {
          ...event,
          recurrenceRule: recurrenceRule || void 0,
          reminders: reminders || []
        },
        message: "\u83B7\u53D6\u4E8B\u4EF6\u6210\u529F"
      });
    } catch (error) {
      console.error("\u83B7\u53D6\u4E8B\u4EF6\u5931\u8D25\uFF1A", error);
      return 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 user = await config.validateAuth(request);
      if (!user) {
        return NextResponse.json({ success: false, error: "\u672A\u6388\u6743\u8BBF\u95EE" }, { status: 401 });
      }
      const eventId = parseInt(params.id);
      if (isNaN(eventId)) {
        return NextResponse.json({ success: false, error: "\u4E8B\u4EF6ID\u65E0\u6548" }, { status: 400 });
      }
      const existingEvent = await calendarDbService.getEventById(eventId);
      if (!existingEvent || existingEvent.userId !== user.id) {
        return 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 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 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 user = await config.validateAuth(request);
      if (!user) {
        return NextResponse.json({ success: false, error: "\u672A\u6388\u6743\u8BBF\u95EE" }, { status: 401 });
      }
      const eventId = parseInt(params.id);
      if (isNaN(eventId)) {
        return NextResponse.json({ success: false, error: "\u4E8B\u4EF6ID\u65E0\u6548" }, { status: 400 });
      }
      const existingEvent = await calendarDbService.getEventById(eventId);
      if (!existingEvent || existingEvent.userId !== user.id) {
        return NextResponse.json({ success: false, error: "\u4E8B\u4EF6\u4E0D\u5B58\u5728\u6216\u65E0\u6743\u5220\u9664" }, { status: 404 });
      }
      await calendarDbService.deleteEvent(eventId);
      return NextResponse.json({
        success: true,
        message: "\u5220\u9664\u4E8B\u4EF6\u6210\u529F"
      });
    } catch (error) {
      console.error("\u5220\u9664\u4E8B\u4EF6\u5931\u8D25\uFF1A", error);
      return 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 user = await config.validateAuth(request);
      if (!user) {
        return 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 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 === user.id) {
            await calendarDbService.deleteEvent(id);
            return true;
          }
          return false;
        })
      );
      const deletedCount = results.filter(Boolean).length;
      return 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 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 user = await config.validateAuth(request);
        if (!user) {
          return NextResponse.json({ success: false, error: "\u672A\u6388\u6743\u8BBF\u95EE" }, { status: 401 });
        }
        const dbConfig = await calendarDbService.getUserConfig(user.id);
        return 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 NextResponse.json({ success: false, error: "\u670D\u52A1\u5668\u5185\u90E8\u9519\u8BEF" }, { status: 500 });
      }
    },
    PUT: async (request) => {
      try {
        const user = await config.validateAuth(request);
        if (!user) {
          return NextResponse.json({ success: false, error: "\u672A\u6388\u6743\u8BBF\u95EE" }, { status: 401 });
        }
        const body = await request.json();
        const updatedConfig = await calendarDbService.upsertUserConfig(user.id, body);
        return 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 NextResponse.json({ success: false, error: "\u670D\u52A1\u5668\u5185\u90E8\u9519\u8BEF" }, { status: 500 });
      }
    }
  };
}

export { createBatchDeleteEventsHandler, createConfigHandler, createCreateEventHandler, createDeleteEventHandler, createGetEventByIdHandler, createGetEventsHandler, createUpdateEventHandler };
//# sourceMappingURL=index.mjs.map
//# sourceMappingURL=index.mjs.map