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

/**
 * Get customers for a user (paginated + optional search)
 * Group B: Customers domain migration
 */
export const getCustomers = query({
  args: {
    userId: v.string(),
    page: v.optional(v.number()),
    limit: v.optional(v.number()),
    search: v.optional(v.string()),
  },
  handler: async (ctx, { userId, page = 1, limit = 20, search }) => {
    const all = await ctx.db
      .query("customers")
      .withIndex("by_userId", (q) => q.eq("userId", userId))
      .collect();

    const filtered = search
      ? all.filter(
          (c) =>
            c.name?.toLowerCase().includes(search.toLowerCase()) ||
            c.phone?.includes(search) ||
            c.email?.toLowerCase().includes(search.toLowerCase()),
        )
      : all;

    const total = filtered.length;
    const start = (page - 1) * limit;
    return {
      customers: filtered.slice(start, start + limit),
      total,
      page,
      totalPages: Math.ceil(total / limit),
    };
  },
});

/**
 * Get a single customer by Convex document ID
 * Group B: Customers domain migration
 */
export const getCustomerById = query({
  args: { id: v.id("customers"), userId: v.string() },
  handler: async (ctx, { id, userId }) => {
    const customer = await ctx.db.get(id);
    if (!customer || customer.userId !== userId) return null;
    return customer;
  },
});

/**
 * Get a customer by phone number within a user/org scope.
 */
export const getByPhone = query({
  args: { userId: v.optional(v.string()), phone: v.string() },
  handler: async (ctx, args) => {
    if (args.userId) {
      return await ctx.db
        .query("customers")
        .withIndex("by_userId_phone", (q: any) =>
          q.eq("userId", args.userId).eq("phone", args.phone),
        )
        .first();
    }
    // Fallback: search by phone only
    return await ctx.db
      .query("customers")
      .withIndex("by_phone", (q: any) => q.eq("phone", args.phone))
      .first();
  },
});
