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

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

  console.log('🚀 ~ POST ~ username:', username)
  console.log('🚀 ~ POST ~ password:', password)

  const user = await prisma.user.findFirst({
    where: {
      username: username,
      password: password,
    },
  })
  console.log('🚀 ~ POST ~ user:', user)

  if (!user) {
    return NextResponse.json({ error: 'User not found' }, { status: 404 })
  }

  const cookieStore = await cookies()
  const session = await getIronSession<SessionData>(cookieStore, sessionOptions)
  console.log('start session edit!')
  // session.username = user.username!
  // session.email = user.email!
  session.isLoggedIn = true
  console.log('end session edit!')
  await session.save()
  console.log('🚀 ~ POST ~ session:', session)

  // return NextResponse.redirect(new URL(process.env.NEXT_PUBLIC_URL!, request.url))
  return NextResponse.json(user)
}
