import { getAuthUserId } from '@convex-dev/auth/server';
import { ConvexError, v } from 'convex/values';

import type { Id } from './_generated/dataModel';
import { mutation, query } from './_generated/server';

export const generateUploadUrl = mutation(async (ctx) => {
  const userId = await getAuthUserId(ctx);
  if (!userId) throw new ConvexError('Not authenticated.');
  return await ctx.storage.generateUploadUrl();
});

const isRemoteImageUrl = (value: string) =>
  value.startsWith('http://') || value.startsWith('https://');

export const getImageUrl = query({
  args: { storageId: v.string() },
  handler: async (ctx, { storageId }) => {
    if (isRemoteImageUrl(storageId)) return storageId;
    try {
      const url = await ctx.storage.getUrl(storageId as Id<'_storage'>);
      return url ?? null;
    } catch {
      return null;
    }
  },
});
