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

/**
 * Get the public URL for a stored file.
 */
export const getFileUrl = query({
  args: {
    storageId: v.id("_storage"),
  },
  handler: async (ctx, args) => {
    return await ctx.storage.getUrl(args.storageId);
  },
});

/**
 * Get file metadata by storage ID.
 */
export const getFileMetadata = query({
  args: {
    storageId: v.id("_storage"),
  },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("file_uploads")
      .withIndex("by_storageId", (q) => q.eq("storageId", args.storageId))
      .first();
  },
});

/**
 * Get all files associated with a specific entity (e.g., all attachments for a contact submission).
 */
export const getFilesByAssociation = query({
  args: {
    entityType: v.string(),
    entityId: v.string(),
  },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("file_uploads")
      .withIndex("by_entityType_entityId", (q) =>
        q.eq("entityType", args.entityType).eq("entityId", args.entityId),
      )
      .collect();
  },
});

/**
 * Get all files in a specific bucket.
 */
export const getFilesByBucket = query({
  args: {
    bucket: v.string(),
  },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("file_uploads")
      .withIndex("by_bucket", (q) => q.eq("bucket", args.bucket))
      .collect();
  },
});
