import "server-only";

import { Query } from "node-appwrite";

import { createAdminClient } from "./server";
import { DATABASE_ID, TABLES, type CalendarEvent } from "./schema";

export async function listCalendarEvents(
  tenantId: string,
  rangeStart?: string,
  rangeEnd?: string,
): Promise<CalendarEvent[]> {
  try {
    const { tablesDB } = createAdminClient();
    const queries = [Query.equal("tenantId", tenantId), Query.limit(1000)];
    if (rangeStart) queries.push(Query.greaterThanEqual("start", rangeStart));
    if (rangeEnd) queries.push(Query.lessThanEqual("start", rangeEnd));
    queries.push(Query.orderAsc("start"));
    const result = await tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.calendarEvents,
      queries,
    });
    return result.rows as unknown as CalendarEvent[];
  } catch {
    return [];
  }
}
