// Auto-generated Lesson routes
import type { FastifyInstance } from "fastify";
import { authenticate } from "../middleware/auth.js";
import { LessonService } from "../services/lesson.js";
import type { CreateLessonInput, UpdateLessonInput } from "../types/index.js";

const service = new LessonService();

export async function lessonsRoutes(app: FastifyInstance): Promise<void> {
  // All routes require authentication
  app.addHook("onRequest", authenticate);

  // GET /api/lessons — list
  app.get("/", async (request, reply) => {
    const items = service.list();
    return { data: items };
  });

  // GET /api/lessons/:id — get by id
  app.get<{ Params: { id: string } }>("/:id", async (request, reply) => {
    const item = service.getById(request.params.id);
    if (!item) {
      return reply.status(404).send({ error: "Not Found", message: "Lesson not found", statusCode: 404 });
    }
    return { data: item };
  });

  // POST /api/lessons — create
  app.post<{ Body: CreateLessonInput }>("/", async (request, reply) => {
    const item = service.create(request.body);
    return reply.status(201).send({ data: item });
  });

  // PUT /api/lessons/:id — update
  app.put<{ Params: { id: string }; Body: UpdateLessonInput }>("/:id", async (request, reply) => {
    const item = service.update(request.params.id, request.body);
    if (!item) {
      return reply.status(404).send({ error: "Not Found", message: "Lesson not found", statusCode: 404 });
    }
    return { data: item };
  });

  // DELETE /api/lessons/:id — delete
  app.delete<{ Params: { id: string } }>("/:id", async (request, reply) => {
    const deleted = service.delete(request.params.id);
    if (!deleted) {
      return reply.status(404).send({ error: "Not Found", message: "Lesson not found", statusCode: 404 });
    }
    return reply.status(204).send();
  });
}
