import type { FastifyInstance } from 'fastify';
import { eq } from 'drizzle-orm';
import { db } from '../db.js';
import { feedback } from '../db/schema.js';

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

    await db
      .insert(feedback)
      .values({
        tv_show_name: body.tv_show_name,
        stars: body.stars,
        feedback: body.feedback ?? '',
      })
      .onConflictDoUpdate({
        target: feedback.tv_show_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);
  });
}
