import { Elysia, t } from 'elysia'
import { prisma } from './prisma'

export const posts = new Elysia({ prefix: '/posts' })
  .get('/', async () => {
    return await prisma.post.findMany({
      include: { user: true },
      orderBy: { createdAt: 'desc' },
    })
  })
  .get('/:id', async ({ params: { id } }) => {
    return await prisma.post.findUnique({
      where: { id },
      include: {
        user: true,
        comments: {
          include: {
            user: true,
          },
          orderBy: {
            createdAt: 'desc',
          },
        },
      },
    })
  })
  .post(
    '/',
    async ({ body }) => {
      return await prisma.post.create({
        data: body,
      })
    },
    {
      body: t.Object({
        title: t.String(),
        content: t.String(),
        userId: t.String(),
        published: t.Optional(t.Boolean()),
      }),
    },
  )
