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

/**
 * Get connected social accounts for a user
 * Phase 5: Social Media
 */
export const getAccounts = query({
  args: { userId: v.string() },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("social_accounts")
      .withIndex("by_userId", (q) => q.eq("userId", args.userId))
      .collect();
  },
});

/**
 * Get content queue for a social account
 * Phase 5: Social Media
 */
export const getContentQueue = query({
  args: {
    socialAccountId: v.string(),
    status: v.optional(v.string()),
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 50;
    return await ctx.db
      .query("social_content_queue")
      .withIndex("by_socialAccountId", (q) =>
        q.eq("socialAccountId", args.socialAccountId),
      )
      .order("desc")
      .take(limit);
  },
});

/**
 * Get analytics for a queue item
 * Phase 5: Social Media
 */
export const getAnalytics = query({
  args: { queueItemId: v.string() },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("social_analytics")
      .withIndex("by_queueItemId", (q) => q.eq("queueItemId", args.queueItemId))
      .unique();
  },
});

/**
 * Get social inbox messages for a user
 * Phase 5: Social Media
 */
export const getMessages = query({
  args: {
    socialAccountId: v.string(),
    conversationId: v.optional(v.string()),
    isRead: v.optional(v.boolean()),
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 50;
    let q = ctx.db
      .query("social_messages")
      .withIndex("by_socialAccountId", (q) =>
        q.eq("socialAccountId", args.socialAccountId),
      );

    if (args.conversationId) {
      q = q.filter((f) => f.eq(f.field("conversationId"), args.conversationId));
    }

    return await q.order("desc").take(limit);
  },
});

/**
 * Get a single social account by ID, scoped to a user
 * Phase 5: Social Media (gap-fill for route wiring)
 */
export const getAccountById = query({
  args: { accountId: v.string(), userId: v.string() },
  handler: async (ctx, args) => {
    // Try as a Convex document ID first
    try {
      const doc = await ctx.db.get(args.accountId as any);
      if (doc && (doc as any).userId === args.userId) {
        return doc;
      }
    } catch {
      // Not a valid Convex ID — fall through to index scan
    }
    // Fall back to scanning by userId and filtering
    const accounts = await ctx.db
      .query("social_accounts")
      .withIndex("by_userId", (q) => q.eq("userId", args.userId))
      .collect();
    return accounts.find((a) => (a as any).prismaId === args.accountId) ?? null;
  },
});

/**
 * Get a social account by userId + platform + platformAccountId (for upsert logic)
 * Phase 5: Social Media (gap-fill for callback route wiring)
 */
export const getAccountByPlatformId = query({
  args: {
    userId: v.string(),
    platform: socialPlatformValidator,
    platformAccountId: v.string(),
  },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("social_accounts")
      .withIndex("by_userId_platform_platformAccountId", (q) =>
        q
          .eq("userId", args.userId)
          .eq("platform", args.platform)
          .eq("platformAccountId", args.platformAccountId),
      )
      .unique();
  },
});

/**
 * Get cached social trends for a user
 * Phase 5: Social Media
 */
export const getTrends = query({
  args: {
    userId: v.string(),
    trendType: v.optional(v.string()),
    platform: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    const now = Date.now();
    let q = ctx.db
      .query("social_trends")
      .withIndex("by_userId", (q) => q.eq("userId", args.userId))
      .filter((f) => f.gt(f.field("expiresAt"), now));

    if (args.trendType) {
      q = q.filter((f) => f.eq(f.field("trendType"), args.trendType));
    }

    return await q.collect();
  },
});
