import { ConvexError, v } from 'convex/values';

import { mutation, query } from './_generated/server';
import {
  getOwnedSpoon,
  getRequiredUserId,
  optionalText,
  requireText,
} from './model';

export const listForSpoon = query({
  args: { spoonId: v.id('spoons') },
  handler: async (ctx, { spoonId }) => {
    const ownerId = await getRequiredUserId(ctx);
    await getOwnedSpoon(ctx, spoonId, ownerId);
    return await ctx.db
      .query('spoonRemotes')
      .withIndex('by_spoon', (q) => q.eq('spoonId', spoonId))
      .order('asc')
      .collect();
  },
});

export const create = mutation({
  args: {
    spoonId: v.id('spoons'),
    label: v.string(),
    url: v.string(),
    remoteName: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    const ownerId = await getRequiredUserId(ctx);
    await getOwnedSpoon(ctx, args.spoonId, ownerId);
    const now = Date.now();
    return await ctx.db.insert('spoonRemotes', {
      spoonId: args.spoonId,
      ownerId,
      label: requireText(args.label, 'Remote label'),
      url: requireText(args.url, 'Remote URL'),
      remoteName: optionalText(args.remoteName),
      createdAt: now,
      updatedAt: now,
    });
  },
});

export const remove = mutation({
  args: { remoteId: v.id('spoonRemotes') },
  handler: async (ctx, { remoteId }) => {
    const ownerId = await getRequiredUserId(ctx);
    const remote = await ctx.db.get(remoteId);
    if (remote?.ownerId !== ownerId) {
      throw new ConvexError('Remote not found.');
    }
    await ctx.db.delete(remoteId);
    return { success: true };
  },
});
