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

export interface VoteSite {
  id: number
  name: string
  url: string
  image_url: string
  points: number
}

export async function listVoteSites(): Promise<VoteSite[]> {
  const [rows] = await db(DB.default).query<RowDataPacket[]>(
    'SELECT id, name, url, image_url, points FROM votesite ORDER BY id',
  )
  return rows.map((r) => ({ id: r.id, name: r.name, url: r.url, image_url: r.image_url, points: r.points }))
}

export async function createVoteSite(name: string, url: string, imageUrl: string, points: number): Promise<number> {
  const [res] = await db(DB.default).query<ResultSetHeader>(
    'INSERT INTO votesite (name, url, image_url, points, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())',
    [name, url, imageUrl, points],
  )
  return res.insertId
}

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