import type { Article } from '$lib/article';
import type { PageServerLoad } from './$types';
import PG from '$lib/server/database';
import { error } from '@sveltejs/kit';

export const load: PageServerLoad = async ({ params, locals }) => {
  const { category, id } = params;
  console.log(id);

  const db = await PG(locals.db);
  await db.begin();
  try {
    const article = await db.query(
      "SELECT * FROM article WHERE id = $1 AND category = $2",
      [id, category]
    );
    if (article.rowCount === 0) {
      error(404, 'Not found');
    }
    const row = article.rows[0];
    const data: Article = { ...row };
    return data
  } catch (e) {
    await db.rollback();
    error(500, (e as Error).message);
  } finally {
    await db.release();
  }
};