import type { ResultSetHeader, RowDataPacket } from 'mysql2'
import { db, DB } from './db'
import { cleanPostHtml } from './forum-sanitize'

export async function createTopic(
  forumId: number,
  name: string,
  poster: string,
  posterId: number,
  text: string,
): Promise<number> {
  const clean = cleanPostHtml(text)
  const [res] = await db(DB.web).query<ResultSetHeader>(
    'INSERT INTO forum_topics (forum_id, name, poster, poster_id, created, created_at, updated_at, locked, sticky, deleted) ' +
      'VALUES (?, ?, ?, ?, NOW(), NOW(), NOW(), 0, 0, 0)',
    [forumId, name, poster, posterId],
  )
  const topicId = res.insertId
  await db(DB.web).query(
    'INSERT INTO forum_posts (topic_id, poster, poster_id, text, time, created_at, deleted) VALUES (?, ?, ?, ?, NOW(), NOW(), 0)',
    [topicId, poster, posterId, clean],
  )
  return topicId
}

export async function createPost(
  topicId: number,
  poster: string,
  posterId: number,
  text: string,
): Promise<number> {
  const clean = cleanPostHtml(text)
  const [res] = await db(DB.web).query<ResultSetHeader>(
    'INSERT INTO forum_posts (topic_id, poster, poster_id, text, time, created_at, deleted) VALUES (?, ?, ?, ?, NOW(), NOW(), 0)',
    [topicId, poster, posterId, clean],
  )
  await db(DB.web).query('UPDATE forum_topics SET updated_at = NOW() WHERE id = ?', [topicId])
  return res.insertId
}

/** Datos mínimos de un post para comprobar permisos (autor + tema). */
export async function getPost(
  postId: number,
): Promise<{ id: number; topic_id: number; poster_id: number | null; text: string } | null> {
  const [rows] = await db(DB.web).query<RowDataPacket[]>(
    'SELECT id, topic_id, poster_id, text FROM forum_posts WHERE id = ? AND deleted = 0',
    [postId],
  )
  const r = rows[0]
  return r ? { id: r.id, topic_id: r.topic_id, poster_id: r.poster_id ?? null, text: r.text } : null
}

/** Edita el texto de un post (ya saneado por el llamador). */
export async function updatePost(postId: number, text: string): Promise<void> {
  const clean = cleanPostHtml(text)
  await db(DB.web).query('UPDATE forum_posts SET text = ?, updated_at = NOW() WHERE id = ?', [clean, postId])
}

/** Marca/desmarca un post como borrado (borrado lógico). */
export async function setPostDeleted(postId: number, deleted: boolean): Promise<void> {
  await db(DB.web).query('UPDATE forum_posts SET deleted = ? WHERE id = ?', [deleted ? 1 : 0, postId])
}

/** Cambia una bandera del tema (sticky/locked/deleted). Solo moderación. */
export async function setTopicFlag(
  topicId: number,
  field: 'sticky' | 'locked' | 'deleted',
  value: boolean,
): Promise<void> {
  if (!['sticky', 'locked', 'deleted'].includes(field)) throw new Error('campo no permitido')
  await db(DB.web).query(`UPDATE forum_topics SET ${field} = ? WHERE id = ?`, [value ? 1 : 0, topicId])
}

/** Mueve un tema a otro foro (marca moved=1). Solo moderación. */
export async function moveTopic(topicId: number, newForumId: number): Promise<void> {
  await db(DB.web).query('UPDATE forum_topics SET forum_id = ?, moved = 1 WHERE id = ?', [newForumId, topicId])
}

/** Comprueba que un foro existe y es visible (para crear tema). */
export async function forumIsPostable(forumId: number): Promise<boolean> {
  const [rows] = await db(DB.web).query<RowDataPacket[]>(
    'SELECT id FROM forums WHERE id = ? AND visibility = 1 AND deleted = 0',
    [forumId],
  )
  return Boolean(rows[0])
}

/** Comprueba que un tema existe y no está cerrado (para responder). */
export async function topicIsReplyable(topicId: number): Promise<boolean> {
  const [rows] = await db(DB.web).query<RowDataPacket[]>(
    'SELECT locked FROM forum_topics WHERE id = ? AND deleted = 0',
    [topicId],
  )
  return Boolean(rows[0] && rows[0].locked !== 1)
}
