import bcrypt from 'bcryptjs';
import { generateToken } from '../index.ts'; // We will import this from index.ts

export const mutationResolvers = {
  signup: async (parent, args, context) => {
    const { email, password, name } = args;

    const existingUser = await context.prisma.User.findUnique({
      where: { email },
    });
    if (existingUser) {
      throw new Error('User already exists');
    }

    const hashedPassword = await bcrypt.hash(password, 10);

    const user = await context.prisma.User.create({
      data: {
        email,
        password: hashedPassword,
        name,
      },
    });

    const token = generateToken(user);

    return {
      token,
      user,
    };
  },

  login: async (parent, args, context) => {
    const { email, password } = args;

    const user = await context.prisma.user.findUnique({
      where: { email },
    });
    if (!user) {
      throw new Error('User not found');
    }

    const isValid = await bcrypt.compare(password, user.password);
    if (!isValid) {
      throw new Error('Invalid password');
    }

    const token = generateToken(user);

    return {
      token,
      user,
    };
  },

  post: (parent, args, context) => {
    if (!context.user) {
      throw new Error('Not authenticated');
    }

    const newLink = context.prisma.link.create({
      data: {
        url: args.url,
        description: args.description,
        postedById: context.user.id,
      },
    });

    return newLink;
  },

  updatePost: async (parent, args, context) => {
    if (!context.user) {
      throw new Error('Not authenticated');
    }

    const { id, description, url } = args;

    const updatedLink = await context.prisma.link.update({
      where: { id },
      data: {
        description,
        url,
      },
    });

    return updatedLink;
  },

  deletePost: async (parent, args, context) => {
    if (!context.user) {
      throw new Error('Not authenticated');
    }

    const { id } = args;

    const link = await context.prisma.link.findUnique({
      where: { id },
    });

    if (!link) {
      throw new Error(`Link with ID ${id} not found`);
    }

    const deletedLink = await context.prisma.link.delete({
      where: { id },
    });

    return deletedLink;
  },
};
