import { v } from "convex/values";
import { query } from "../_generated/server";

/**
 * Get all appointment types for an organization.
 */
export const getByOrganization = query({
  args: { organizationId: v.string() },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("appointment_types")
      .withIndex("by_organizationId", (q) =>
        q.eq("organizationId", args.organizationId),
      )
      .collect();
  },
});

/**
 * Get active appointment types for an organization, ordered by sortOrder.
 */
export const getActiveByOrganization = query({
  args: { organizationId: v.string() },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("appointment_types")
      .withIndex("by_organizationId_isActive", (q) =>
        q.eq("organizationId", args.organizationId).eq("isActive", true),
      )
      .collect();
  },
});

/**
 * List appointment types for an organization (adapter-compatible).
 * Accepts optional isActive filter for the Prisma-Convex adapter.
 */
export const list = query({
  args: {
    organizationId: v.optional(v.string()),
    isActive: v.optional(v.boolean()),
  },
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  handler: async (ctx, args: any) => {
    if (!args.organizationId) return [];
    if (args.isActive === true) {
      return await ctx.db
        .query("appointment_types")
        .withIndex("by_organizationId_isActive", (q: any) =>
          q.eq("organizationId", args.organizationId).eq("isActive", true),
        )
        .collect();
    }
    return await ctx.db
      .query("appointment_types")
      .withIndex("by_organizationId", (q: any) =>
        q.eq("organizationId", args.organizationId),
      )
      .collect();
  },
});

/**
 * Get a single appointment type by ID.
 */
export const getById = query({
  args: { id: v.id("appointment_types") },
  handler: async (ctx, args) => {
    return await ctx.db.get(args.id);
  },
});
