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

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

export const blockedUser = mysqlTable('blocked_user', {
  id: int('id').primaryKey().autoincrement(),
  uuid: varchar('uuid', { length: 255 }).unique().notNull(),
  comment: varchar('comment', { length: 255 })
});

export type AddBlockedUserReq = {
  uuid: string;
  comment?: string | null;
};

export type EditBlockedUserReq = {
  id: number;
  uuid: string;
  comment?: string | null;
};

export type DeleteBlockedUserReq = {
  id: number;
};

export type GetBlockedUserByUuidReq = {
  uuid: string;
};

export type GetBlockedUsersReq = {};

export async function addBlockedUser(db: Database, values: AddBlockedUserReq) {
  const bu = await db.insert(blockedUser).values(values).$returningId();

  return bu[0];
}

export async function editBlockedUser(db: Database, values: EditBlockedUserReq) {
  await db.update(blockedUser).set(values).where(eq(blockedUser.id, values.id));
}

export async function deleteBlockedUser(db: Database, values: DeleteBlockedUserReq) {
  return db.delete(blockedUser).where(eq(blockedUser.id, values.id));
}

export async function getBlockedUserByUuid(db: Database, values: GetBlockedUserByUuidReq) {
  const bu = await db.query.blockedUser.findFirst({
    where: eq(blockedUser.uuid, values.uuid)
  });

  return bu ?? null;
}

export async function getBlockedUsers(db: Database, _values: GetBlockedUsersReq) {
  return db.select().from(blockedUser);
}
