import { int, mysqlTable, tinyint, varchar } from 'drizzle-orm/mysql-core';
import type { MySql2Database } from 'drizzle-orm/mysql2';
import { asc, eq } from 'drizzle-orm';

type Database = MySql2Database<{ strikeReason: typeof strikeReason }>;

export const strikeReason = mysqlTable('strike_reason', {
  id: int('id').primaryKey().autoincrement(),
  name: varchar('name', { length: 255 }).notNull(),
  weight: tinyint('weight').notNull()
});

export type AddStrikeReasonReq = {
  name: string;
  weight: number;
};

export type EditStrikeReasonReq = typeof strikeReason.$inferSelect;

export type DeleteStrikeReasonReq = {
  id: number;
};

export type GetStrikeReasonsReq = {};

export async function addStrikeReason(db: Database, values: AddStrikeReasonReq) {
  const sr = await db.insert(strikeReason).values(values).$returningId();

  return sr[0];
}

export async function editStrikeReason(db: Database, values: EditStrikeReasonReq) {
  await db.update(strikeReason).set(values).where(eq(strikeReason.id, values.id));
}

export async function deleteStrikeReason(db: Database, values: DeleteStrikeReasonReq) {
  await db.delete(strikeReason).where(eq(strikeReason.id, values.id));
}

export async function getStrikeReasons(db: Database, _values: GetStrikeReasonsReq) {
  return db.select().from(strikeReason).orderBy(asc(strikeReason.weight));
}
