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

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

export const settings = mysqlTable('settings', {
  name: varchar('name', { length: 255 }).unique().notNull(),
  value: text()
});

export type GetSettingsReq = {
  names?: string[];
};

export type SetSettingsReq = {
  settings: {
    name: string;
    value: string | null;
  }[];
};

export type GetSettingReq = {
  name: string;
};

export async function getSettings(db: Database, values: GetSettingsReq) {
  return db
    .select({ name: settings.name, value: settings.value })
    .from(settings)
    .where(values.names ? inArray(settings.name, values.names) : undefined);
}

export async function setSettings(db: Database, values: SetSettingsReq) {
  return db.transaction(async (tx) => {
    for (const setting of values.settings) {
      await tx
        .insert(settings)
        .values(setting)
        .onDuplicateKeyUpdate({
          set: {
            value: setting.value
          }
        });
    }
  });
}

export async function getSetting(db: Database, values: GetSettingReq): Promise<string | null> {
  const value = await db.select({ value: settings.value }).from(settings).where(eq(settings.name, values.name));
  return value.length > 0 ? value[0]?.value : null;
}
