import { NextRequest, NextResponse } from "next/server";
import { Pool } from "pg"

const db = new Pool({
  connectionString: process.env.DB_STRING
})


export async function GET(req: NextRequest){
  try{

    const result = await db.query("SELECT * from products");
    return NextResponse.json(result.rows ?? []);
  } catch(error){

    return NextResponse.json({ message: "Serverside eception occurred" }, { status: 500 })
  }
}

export async function POST(req: NextRequest){
  try{
    const body = (await req.json()) as { name: string, expiration_date: string }
    console.log("GOT BODY:", body)
    const result = await db.query("INSERT INTO products (name, exp_date) VALUES ($1, $2) RETURNING record_num;", [name, expiration_date]);
    return NextResponse.json(result.rows[0].record_num ?? []);
  } catch(error){

    return NextResponse.json({ message: "Serverside eception occurred" }, { status: 500 })
  }
}
