import type { SessionData } from '@/types/Auth'
import { NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import { prisma } from '@/libs/prisma'
import { getIronSession } from 'iron-session'
import { sessionOptions } from '@/libs/session'

export async function POST(request: Request) {
  const { url, data } = await request.json()

  const cookieStore = await cookies()
  const session = await getIronSession<SessionData>(cookieStore, sessionOptions)

  let owner = ''
  if (url === '/api/auth/login') {
    owner = 'Login'
  } else if (url === '/api/auth/logout') {
    owner = 'Logout'
  } else {
    owner = session.userId ?? 'Direct'
  }

  let type = ''
  if (url.includes('api')) {
    type = 'api'
  } else {
    type = 'page'
  }

  // @ts-ignore
  const result = await prisma.MS_USR_TRK.create({
    data: {
      OWNER: owner,
      TYPE: type,
      URL: url,
      DATA: JSON.stringify(data),
    },
  })

  return NextResponse.json({ message: 'Tracking data received', result })
}
