import Knex, { QueryBuilder } from "knex";
import { User } from "../common/common-types";

export interface IUserRepository {
  knex: Knex;
  create: (data: User) => QueryBuilder;
  update: (id: string, data: User) => QueryBuilder;
  delete: (id: string) => QueryBuilder;
  deleteAllUsers: () => QueryBuilder;
  verifyUser: (login: string) => QueryBuilder;
  getAll: () => QueryBuilder;
  getUser: (login: string) => QueryBuilder;
}

export class UserRepository implements IUserRepository {
  knex: Knex;
  constructor(knex: Knex) {
    this.knex = knex;
  }

  verifyUser(login: string) {
    return this.knex("users").where("login", login);
  }

  create(data: User) {
    return this.knex("users").insert(data);
  }

  getAll() {
    return this.knex("users");
  }

  getUser(login: string) {
    return this.knex("users").where("login", login);
  }

  update(login: string, data: User) {
    return this.knex("users")
      .where("login", login)
      .update(data);
  }

  delete(login: string) {
    return this.knex("users")
      .where("login", login)
      .del();
  }

  deleteAllUsers() {
    return this.knex("users").del();
  }
}
