import type { FastifyInstance } from 'fastify';
import { db } from '../db.js';
import { feedback } from '../db/schema.js';

export default async function feedbackRoute(fastify: FastifyInstance) {
  // POST /feedback — upsert by item_name
  fastify.post('/feedback', async (request, reply) => {
    const body = request.body as {
      item_name: string;
      stars: number;
      feedback?: string;
    };

    await db
      .insert(feedback)
      .values({
        item_name: body.item_name,
        stars: body.stars,
        feedback: body.feedback ?? '',
      })
      .onConflictDoUpdate({
        target: feedback.item_name,
        set: {
          stars: body.stars,
          feedback: body.feedback ?? '',
        },
      });

    return reply.code(201).send({ ok: true });
  });

  // GET /feedback — return all feedback entries
  fastify.get('/feedback', async (_request, reply) => {
    const rows = await db.select().from(feedback);
    return reply.send(rows);
  });
}
