import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'

const VALID_TYPES = [
  'PETICAO_INICIAL', 'CONTESTACAO', 'APELACAO', 'RECURSO',
  'CONTRATO', 'PARECER', 'IMPUGNACAO', 'HABEAS_CORPUS',
  'MANDADO_SEGURANCA', 'OUTROS',
]

const VALID_AREAS = [
  'CIVIL', 'TRABALHISTA', 'PENAL', 'TRIBUTARIO',
  'FAMILIA', 'EMPRESARIAL', 'CONSUMIDOR', 'ADMINISTRATIVO',
]

export async function GET(req: NextRequest) {
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })
  }

  const { searchParams } = new URL(req.url)
  const type = searchParams.get('type')
  const area = searchParams.get('area')
  const search = searchParams.get('search')

  // Return public templates + user's own templates
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const where: any = {
    OR: [
      { isPublic: true },
      { userId: session.user.id },
    ],
  }

  if (type) where.type = type
  if (area) where.area = area
  if (search) {
    where.AND = [
      {
        OR: [
          { name: { contains: search } },
          { description: { contains: search } },
        ],
      },
    ]
  }

  const templates = await prisma.template.findMany({
    where,
    orderBy: [
      { isPublic: 'desc' },
      { createdAt: 'desc' },
    ],
    select: {
      id: true,
      name: true,
      description: true,
      type: true,
      area: true,
      prompt: true,
      isPublic: true,
      userId: true,
      createdAt: true,
    },
  })

  return NextResponse.json({ templates })
}

export async function POST(req: NextRequest) {
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })
  }

  try {
    const body = await req.json()
    const { name, description, type, area, prompt } = body

    if (!name || !description || !type || !area || !prompt) {
      return NextResponse.json(
        { error: 'Todos os campos são obrigatórios: name, description, type, area, prompt' },
        { status: 400 }
      )
    }

    if (!VALID_TYPES.includes(type)) {
      return NextResponse.json({ error: `Tipo inválido. Tipos válidos: ${VALID_TYPES.join(', ')}` }, { status: 400 })
    }

    if (!VALID_AREAS.includes(area)) {
      return NextResponse.json({ error: `Área inválida. Áreas válidas: ${VALID_AREAS.join(', ')}` }, { status: 400 })
    }

    const template = await prisma.template.create({
      data: {
        name,
        description,
        type,
        area,
        prompt,
        isPublic: false,
        userId: session.user.id,
      },
    })

    return NextResponse.json({ template }, { status: 201 })
  } catch {
    return NextResponse.json({ error: 'Erro ao criar modelo' }, { status: 500 })
  }
}
