import { GraphQLClient } from 'graphql-request';
import {
  GetUserQueryVariables,
  CreateUserMutationVariables,
  UpdateUserMutationVariables,
  DeleteUserMutationVariables,
  UserWhereUniqueInput,
} from '../gql/graphql';
import { graphql } from '../gql';
import { BaseFunctions } from './BaseFunctions';

class UserFunctions extends BaseFunctions {
  
  constructor(client: GraphQLClient) {
    super(client);
  }

  async getUser(where: UserWhereUniqueInput) {
    const query = graphql(`
      query GetUser($where: UserWhereUniqueInput!) {
        user(where: $where) {
          id
          name
          role
          apiKey
          email
        }
      }
    `);

    return this.request(query, { where });
  }

  async createUser(userData: CreateUserMutationVariables['data']) {
    const mutation = graphql(`
      mutation CreateUser($data: UserCreateInput!) {
        createOneUser(data: $data) {
          id
          name
          role
          apiKey
          email
        }
      }
    `);

    return this.request(mutation, { data: userData });
  }

  async updateUser(userId: number, userData: UpdateUserMutationVariables['data']) {
    const mutation = graphql(`
      mutation UpdateUser($where: UserWhereUniqueInput!, $data: UserUpdateInput!) {
        updateOneUser(where: $where, data: $data) {
          id
          name
          role
          apiKey
          email
        }
      }
    `);

    const variables: UpdateUserMutationVariables = {
      where: { id: userId },
      data: userData,
    };
    return this.request(mutation, variables);
  }

  async deleteUser(userId: number) {
    const mutation = graphql(`
      mutation DeleteUser($where: UserWhereUniqueInput!) {
        deleteOneUser(where: $where) {
          id
        }
      }
    `);

    const variables: DeleteUserMutationVariables = { where: { id: userId } };
    return this.request(mutation, variables);
  }
}

export { UserFunctions };
