import type { CurrentUser, Env, SiteSettings } from '../env';
import { all } from '../db/queries';
import { mediaUrl } from '../utils/image';
import { nowSeconds } from '../utils/time';

export async function likePost(env: Env['Bindings'], postId: string, user: CurrentUser): Promise<{ already: boolean; likeCount: number }> {
  const result = await env.DB.prepare('INSERT OR IGNORE INTO wm_likes(post_id, user_id, created_at) VALUES (?, ?, ?)')
    .bind(postId, user.id, nowSeconds())
    .run();
  const count = await env.DB.prepare('SELECT like_count FROM wm_posts WHERE id = ?').bind(postId).first<{ like_count: number }>();
  return { already: result.meta.changes === 0, likeCount: count?.like_count || 0 };
}

export async function unlikePost(env: Env['Bindings'], postId: string, user: CurrentUser): Promise<{ likeCount: number }> {
  await env.DB.prepare('DELETE FROM wm_likes WHERE post_id = ? AND user_id = ?').bind(postId, user.id).run();
  const count = await env.DB.prepare('SELECT like_count FROM wm_posts WHERE id = ?').bind(postId).first<{ like_count: number }>();
  return { likeCount: count?.like_count || 0 };
}

export async function listLikes(env: Env['Bindings'], settings: SiteSettings, postId: string): Promise<{
  users: Array<{ id: string; username: string; displayName: string; avatarUrl: string }>;
  count: number;
}> {
  const rows = await all<{ id: string; username: string; display_name: string; avatar_key: string | null }>(
    env.DB.prepare(
      `SELECT u.id, u.username, u.display_name, u.avatar_key
       FROM wm_likes l JOIN wm_users u ON u.id = l.user_id
       WHERE l.post_id = ?
       ORDER BY l.created_at ASC
       LIMIT 8`
    ).bind(postId)
  );
  const count = await env.DB.prepare('SELECT like_count FROM wm_posts WHERE id = ?').bind(postId).first<{ like_count: number }>();
  return {
    users: rows.map((row) => ({
      id: row.id,
      username: row.username,
      displayName: row.display_name,
      avatarUrl: mediaUrl(settings.cdn_base_url, row.avatar_key)
    })),
    count: count?.like_count || 0
  };
}
