import { NextRequest, NextResponse } from "next/server";
import { prisma } from "prisma/client";
import { cookies } from "next/headers"
import { Credential } from "@/common/types/auth"
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";

const JWT_SECRET = process.env.JWT_SECRET as string

export async function POST(request: NextRequest) {
  const body = await request.json()

  const user = await prisma.user.findUnique({
    where: { username: body.username },
    include: {
      company: true
    }
  })

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

  if (!await bcrypt.compare(body.password, user.password)) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const credential: Credential = {
    ...user,
    token: jwt.sign(user, JWT_SECRET, { expiresIn: '10y' })
  }

  cookies().set('credential', JSON.stringify(credential), { secure: true, expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30) })

  return NextResponse.json(credential)
}