import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { prisma } from '@shieldai/db';

interface BlogQuery {
  page?: string;
  limit?: string;
  tag?: string;
}

export async function blogRoutes(fastify: FastifyInstance) {
  fastify.get('/blog', async (request: FastifyRequest, reply: FastifyReply) => {
    const query = request.query as BlogQuery;
    const page = Math.max(1, parseInt(query.page || '1', 10));
    const limit = Math.min(50, Math.max(1, parseInt(query.limit || '10', 10)));
    const skip = (page - 1) * limit;

    const where = {
      published: true,
      ...(query.tag ? { tags: { has: query.tag } } : {}),
    };

    const [posts, total] = await Promise.all([
      prisma.blogPost.findMany({
        where,
        orderBy: { publishedAt: 'desc' },
        skip,
        take: limit,
        select: {
          id: true,
          slug: true,
          title: true,
          excerpt: true,
          authorName: true,
          coverImageUrl: true,
          tags: true,
          publishedAt: true,
          viewCount: true,
        },
      }),
      prisma.blogPost.count({ where }),
    ]);

    return reply.send({
      posts,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  });

  fastify.get('/blog/:slug', async (request: FastifyRequest, reply: FastifyReply) => {
    const { slug } = request.params as { slug: string };

    const post = await prisma.blogPost.findUnique({
      where: { slug },
    });

    if (!post || !post.published) {
      return reply.code(404).send({ error: 'Post not found' });
    }

    await prisma.blogPost.update({
      where: { id: post.id },
      data: { viewCount: { increment: 1 } },
    });

    return reply.send({ post });
  });
}
