/**
 * API de Acesso a Ticket por Token
 * GET - Valida token e retorna informações do ticket
 * POST - Marca token como usado e cria sessão temporária
 */

import { NextRequest, NextResponse } from "next/server"
import { prisma } from "@/lib/prisma"
import { validateAccessToken, markTokenAsUsed } from "@/server/notification"

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ token: string }> }
) {
  try {
    const { token } = await params

    // Valida o token
    const validatedToken = await validateAccessToken(token)

    if (!validatedToken) {
      return NextResponse.json(
        { error: "Token inválido ou expirado" },
        { status: 401 }
      )
    }

    // Busca informações do ticket
    const ticket = await prisma.ticket.findUnique({
      where: { id: validatedToken.ticketId },
      include: {
        requester: {
          select: {
            id: true,
            name: true,
            email: true,
          },
        },
        assignee: {
          select: {
            id: true,
            name: true,
          },
        },
        company: {
          select: {
            id: true,
            name: true,
          },
        },
        comments: {
          where: {
            visibility: "PUBLIC",
          },
          orderBy: {
            createdAt: "desc",
          },
          take: 10,
          include: {
            author: {
              select: {
                id: true,
                name: true,
              },
            },
          },
        },
        rating: true,
      },
    })

    if (!ticket) {
      return NextResponse.json(
        { error: "Chamado não encontrado" },
        { status: 404 }
      )
    }

    // Verifica se o usuário tem acesso ao ticket
    if (
      ticket.requesterId !== validatedToken.userId &&
      ticket.assigneeId !== validatedToken.userId
    ) {
      return NextResponse.json(
        { error: "Acesso negado a este chamado" },
        { status: 403 }
      )
    }

    return NextResponse.json({
      token: {
        id: validatedToken.id,
        scope: validatedToken.scope,
        expiresAt: validatedToken.expiresAt.toISOString(),
        used: validatedToken.usedAt !== null,
      },
      ticket: {
        id: ticket.id,
        reference: ticket.reference,
        subject: ticket.subject,
        summary: ticket.summary,
        status: ticket.status,
        priority: ticket.priority,
        channel: ticket.channel,
        createdAt: ticket.createdAt.toISOString(),
        resolvedAt: ticket.resolvedAt?.toISOString() ?? null,
        requester: {
          id: ticket.requester.id,
          name: ticket.requester.name,
        },
        assignee: ticket.assignee
          ? {
              id: ticket.assignee.id,
              name: ticket.assignee.name,
            }
          : null,
        company: ticket.company
          ? {
              id: ticket.company.id,
              name: ticket.company.name,
            }
          : null,
        comments: ticket.comments.map((comment) => ({
          id: comment.id,
          body: comment.body,
          createdAt: comment.createdAt.toISOString(),
          author: {
            id: comment.author.id,
            name: comment.author.name,
          },
        })),
        rating: ticket.rating
          ? {
              rating: ticket.rating.rating,
              comment: ticket.rating.comment,
              createdAt: ticket.rating.createdAt.toISOString(),
            }
          : null,
      },
    })
  } catch (error) {
    console.error("[ticket-access] Erro ao validar token:", error)
    return NextResponse.json(
      { error: "Erro interno do servidor" },
      { status: 500 }
    )
  }
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ token: string }> }
) {
  try {
    const { token } = await params

    // Valida o token
    const validatedToken = await validateAccessToken(token)

    if (!validatedToken) {
      return NextResponse.json(
        { error: "Token inválido ou expirado" },
        { status: 401 }
      )
    }

    // Marca o token como usado
    await markTokenAsUsed(token)

    return NextResponse.json({
      success: true,
      message: "Token marcado como usado",
    })
  } catch (error) {
    console.error("[ticket-access] Erro ao usar token:", error)
    return NextResponse.json(
      { error: "Erro interno do servidor" },
      { status: 500 }
    )
  }
}
