import type { FastifyInstance } from 'fastify';
import { getPocketBase } from '../lib/pocketbase.js';
import { PublishBodySchema } from '../types.js';

export async function publishRoutes(app: FastifyInstance): Promise<void> {
  app.patch<{ Params: { id: string } }>('/micro-learnings/:id', async (request, reply) => {
    const parsed = PublishBodySchema.safeParse(request.body);
    if (!parsed.success) {
      return reply.status(400).send({ error: 'invalid request', details: parsed.error.issues });
    }

    const { id } = request.params;
    const { status: newStatus } = parsed.data;

    const pb = await getPocketBase();

    let existing: Record<string, unknown>;
    try {
      existing = await pb.collection('micro_learnings').getOne(id) as Record<string, unknown>;
    } catch {
      return reply.status(404).send({ error: 'micro learning not found' });
    }

    if (existing['status'] !== 'generated') {
      return reply.status(400).send({
        error: 'only generated records can be published or rejected',
        currentStatus: existing['status'],
      });
    }

    const updates: Record<string, unknown> = { status: newStatus };
    if (newStatus === 'published') {
      updates['published_at'] = new Date().toISOString();
    }

    const updated = await pb.collection('micro_learnings').update(id, updates);

    return reply.send({
      id: updated.id,
      status: updated['status'],
      published_at: updated['published_at'] ?? null,
    });
  });
}
