import { query } from '../db/connection.js';
import { ulid } from 'ulid';

export async function listNotes(recipeId: string, userId?: string) {
  if (!userId) {
    const { rows } = await query('SELECT * FROM notes WHERE recipe_id = $1 AND user_id IS NULL ORDER BY created_at DESC', [recipeId]);
    return rows;
  }
  const { rows } = await query('SELECT * FROM notes WHERE recipe_id = $1 AND user_id = $2 ORDER BY created_at DESC', [recipeId, userId]);
  return rows;
}

export async function createNote(recipeId: string, content: string, userId?: string) {
  const { rows: recipe } = await query('SELECT id FROM recipes WHERE id = $1', [recipeId]);
  if (recipe.length === 0) return null;

  const id = ulid();
  await query('INSERT INTO notes (id, recipe_id, content, user_id) VALUES ($1, $2, $3, $4)', [id, recipeId, content, userId || null]);
  const { rows } = await query('SELECT * FROM notes WHERE id = $1', [id]);
  return rows[0];
}

export async function updateNote(id: string, content: string, userId?: string) {
  let sql: string;
  let params: any[];

  if (!userId) {
    sql = 'UPDATE notes SET content = $1 WHERE id = $2 AND user_id IS NULL';
    params = [content, id];
  } else {
    sql = 'UPDATE notes SET content = $1 WHERE id = $2 AND user_id = $3';
    params = [content, id, userId];
  }

  const result = await query(sql, params);
  if ((result.rowCount ?? 0) === 0) return null;
  const { rows } = await query('SELECT * FROM notes WHERE id = $1', [id]);
  return rows[0];
}

export async function deleteNote(id: string, userId?: string): Promise<boolean> {
  let sql: string;
  let params: any[];

  if (!userId) {
    sql = 'DELETE FROM notes WHERE id = $1 AND user_id IS NULL';
    params = [id];
  } else {
    sql = 'DELETE FROM notes WHERE id = $1 AND user_id = $2';
    params = [id, userId];
  }

  const result = await query(sql, params);
  return (result.rowCount ?? 0) > 0;
}
