import Knex, { QueryBuilder } from "knex";
import { Ticket, TicketType } from "../common/common-types";
import { ticketTypeLabelMaker } from "../utils/label-makers";
import { getTicketPrice } from "../utils/get-price";

export interface ITicketRepository {
  knex: Knex;
  create: (id: string, data: Ticket) => QueryBuilder;
  createMultiple: (data: Ticket[]) => QueryBuilder;
  delete: (id: string) => QueryBuilder;
  deleteAllTickets: () => QueryBuilder;
  validate: (id: string) => QueryBuilder;
  createType: (id: string, data: object) => QueryBuilder;
  deleteTicketType: (id: string) => QueryBuilder;
  deleteAllTicketTypes: () => QueryBuilder;
  getAllTicketTypes: () => QueryBuilder;
}

export class TicketRepository implements ITicketRepository {
  knex: Knex;
  constructor(knex: Knex) {
    this.knex = knex;
  }

  create(id: string, data: Ticket) {
    return this.knex("tickets").insert({ id: id, name: data.name });
  }

  createMultiple(data: Ticket[]) {
    return this.knex("tickets").insert(data, ["id"]);
  }

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

  deleteAllTickets() {
    return this.knex("tickets").del();
  }

  validate(id: string) {
    return this.knex("tickets").where("id", id);
  }

  createType(id: string, data: TicketType) {
    const label = ticketTypeLabelMaker(data);
    const price = getTicketPrice(data);

    return this.knex("ticket_types").insert({
      id,
      tariff: data.tariff,
      type: data.type,
      label,
      entries: data.number_of_entries,
      price,
    });
  }

  deleteTicketType(id: string) {
    return this.knex("ticket_types")
      .where("id", id)
      .del();
  }

  deleteAllTicketTypes() {
    return this.knex("ticket_types").del();
  }

  getAllTicketTypes() {
    return this.knex("ticket_types");
  }
}
