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

const COOLDOWN_MS = (12 * 60 + 30) * 60 * 1000 // 12h 30m

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

export interface VoteResult {
  success: boolean
  error?: string
  points?: number
  siteName?: string
  hours?: number
  minutes?: number
}

export async function getVoteSites(): Promise<VoteSite[]> {
  try {
    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 }))
  } catch {
    return []
  }
}

export interface VoteSiteStatus extends VoteSite {
  lastVoteAt: string | null // ISO del último voto de la cuenta en este sitio, o null
  onCooldown: boolean // true si aún no puede volver a votar (dentro de las 12h30m)
}

/** Sitios de votación con la fecha del último voto de la cuenta (para el recuadro). */
export async function getVoteSitesForAccount(accountId: number): Promise<VoteSiteStatus[]> {
  const sites = await getVoteSites()
  if (!accountId) return sites.map((s) => ({ ...s, lastVoteAt: null, onCooldown: false }))
  try {
    const [rows] = await db(DB.default).query<RowDataPacket[]>(
      'SELECT vote_site_id, MAX(created_at) AS last FROM votelog WHERE account_id = ? GROUP BY vote_site_id',
      [accountId],
    )
    const map = new Map(rows.map((r) => [Number(r.vote_site_id), r.last as Date]))
    return sites.map((s) => {
      const last = map.get(s.id)
      const lastMs = last ? new Date(last).getTime() : 0
      return {
        ...s,
        lastVoteAt: last ? new Date(last).toISOString() : null,
        onCooldown: lastMs > 0 && Date.now() - lastMs < COOLDOWN_MS,
      }
    })
  } catch {
    return sites.map((s) => ({ ...s, lastVoteAt: null, onCooldown: false }))
  }
}

export async function registerVote(accountId: number, url: string): Promise<VoteResult> {
  const [siteRows] = await db(DB.default).query<RowDataPacket[]>(
    'SELECT id, name, points FROM votesite WHERE url = ?',
    [url],
  )
  const site = siteRows[0]
  if (!site) return { success: false, error: 'siteNotFound' }

  const [last] = await db(DB.default).query<RowDataPacket[]>(
    'SELECT created_at FROM votelog WHERE account_id = ? AND vote_site_id = ? ORDER BY created_at DESC LIMIT 1',
    [accountId, site.id],
  )
  if (last[0]) {
    const diff = Date.now() - new Date(last[0].created_at).getTime()
    if (diff < COOLDOWN_MS) {
      const rem = COOLDOWN_MS - diff
      return { success: false, error: 'cooldown', hours: Math.floor(rem / 3600000), minutes: Math.floor((rem % 3600000) / 60000) }
    }
  }

  // Acreditar PV
  const [pts] = await db(DB.default).query<RowDataPacket[]>('SELECT id FROM api_points WHERE accountID = ?', [accountId])
  if (pts[0]) {
    await db(DB.default).query('UPDATE api_points SET vp = vp + ? WHERE accountID = ?', [site.points, accountId])
  } else {
    await db(DB.default).query('INSERT INTO api_points (accountID, vp, dp) VALUES (?, ?, 0)', [accountId, site.points])
  }

  await db(DB.default).query(
    'INSERT INTO votelog (account_id, vote_site_id, created_at, last_vote_time, processed) VALUES (?, ?, NOW(), NOW(), 0)',
    [accountId, site.id],
  )

  return { success: true, points: site.points, siteName: site.name }
}
