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

/**
 * Generate an upload URL for client-side file uploads.
 * The client uploads the file directly to Convex storage using this URL.
 */
export const generateUploadUrl = mutation({
  args: {},
  handler: async (ctx) => {
    return await ctx.storage.generateUploadUrl();
  },
});

/**
 * Save file metadata after a successful upload.
 * Called after the client uploads a file using the URL from generateUploadUrl.
 */
export const saveFileMetadata = mutation({
  args: {
    storageId: v.id("_storage"),
    fileName: v.string(),
    fileType: v.string(),
    fileSize: v.number(),
    bucket: v.string(),
    uploadedBy: v.optional(v.string()),
    entityId: v.optional(v.string()),
    entityType: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    const id = await ctx.db.insert("file_uploads", {
      storageId: args.storageId,
      fileName: args.fileName,
      fileType: args.fileType,
      fileSize: args.fileSize,
      bucket: args.bucket,
      uploadedBy: args.uploadedBy,
      entityId: args.entityId,
      entityType: args.entityType,
      createdAt: Date.now(),
    });
    return id;
  },
});

/**
 * Delete a file from storage and remove its metadata record.
 */
export const deleteFile = mutation({
  args: {
    storageId: v.id("_storage"),
  },
  handler: async (ctx, args) => {
    // Delete from Convex storage
    await ctx.storage.delete(args.storageId);

    // Delete metadata record
    const metadata = await ctx.db
      .query("file_uploads")
      .withIndex("by_storageId", (q) => q.eq("storageId", args.storageId))
      .first();

    if (metadata) {
      await ctx.db.delete(metadata._id);
    }
  },
});

/**
 * Delete file metadata by its document ID (without deleting from storage).
 */
export const deleteFileMetadata = mutation({
  args: {
    id: v.id("file_uploads"),
  },
  handler: async (ctx, args) => {
    await ctx.db.delete(args.id);
  },
});
