import type { RowDataPacket, ResultSetHeader } from 'mysql2'
import { db, DB } from './db'

export interface RecruitReward {
  id: number
  required_friends: number
  reward_name: string
  item_id: number
  item_quantity: number
  item_link: string
  icon_class: string
}

export async function listRecruitRewards(): Promise<RecruitReward[]> {
  const [rows] = await db(DB.default).query<RowDataPacket[]>(
    'SELECT id, required_friends, reward_name, item_id, item_quantity, item_link, icon_class FROM recruitreward ORDER BY required_friends, id',
  )
  return rows.map((r) => ({
    id: r.id,
    required_friends: r.required_friends,
    reward_name: r.reward_name,
    item_id: r.item_id,
    item_quantity: r.item_quantity,
    item_link: r.item_link,
    icon_class: r.icon_class,
  }))
}

export async function createRecruitReward(data: Omit<RecruitReward, 'id'>): Promise<number> {
  const [res] = await db(DB.default).query<ResultSetHeader>(
    `INSERT INTO recruitreward
       (required_friends, reward_name, item_id, item_quantity, item_link, icon_class)
     VALUES (?, ?, ?, ?, ?, ?)`,
    [data.required_friends, data.reward_name, data.item_id, data.item_quantity, data.item_link, data.icon_class],
  )
  return res.insertId
}

export async function deleteRecruitReward(id: number): Promise<void> {
  await db(DB.default).query('DELETE FROM recruitreward WHERE id = ?', [id])
}
