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, firstName } = args;

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

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

    const account = await context.prisma.Account.create({
      data: {
        email,
        password: hashedPassword,
        firstName,
      },
    });

    

    const token = generateToken(account);
    console.log('Account Data:', account);
    return {
      token,
      account,
    };
    
  },

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

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

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

    const token = generateToken(account);

    return {
      token,
      account,
    };
  },
/*
  post: (parent, args, context) => {
    if (!context.authenticate) {
      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.authenticate) {
      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.authenticate) {
      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;
  },
  */
};
