import prisma from "@/lib/prisma";
import { NextRequest, NextResponse } from "next/server";
import bcrypt from "bcrypt"
import { generateRefreshToken } from "@/utils/refreshToken";
import { serialize } from "cookie";
import { auth } from "@/middleware/auth";

export const userCtrl = {
    register: async (req: NextRequest) => {
        const {email, username, password} = await req.json()

        const emailTest = await prisma.user.findFirst({where: { email: email }})

        if(emailTest){
            return NextResponse.json({err: "Epasta adrese tiek jau izmantota"}, { status: 400 })
        }

        const usernameTest = await prisma.user.findFirst({where: { username: username }})

        if(usernameTest){
            return NextResponse.json({err: "Lietotājvārds jau aziņemts"}, { status: 400 })
        }

        const passwordHash = await bcrypt.hash(password, 12)

        const user = await prisma.user.create({ data: { email, username, password: passwordHash, role: 0 } })

        const refreshToken = generateRefreshToken(user.id)

        const cookie = serialize("refresh-token", refreshToken, {
            httpOnly: true,
            secure: process.env.NODE_ENV === "production",
            maxAge: 60 * 60 * 24,
            path: "/" 
        })

        return NextResponse.json(user, {
            status: 200,
            headers: {
                "Set-Cookie": cookie
            }
        })
    },
    login: async (req: NextRequest) => {
        const { username, password } = await req.json()

        const user = await prisma.user.findFirst({where: { username: username }})

        if(!user){
            return NextResponse.json({err: "Lietotājs netika atrasts"}, { status: 400 })
        }

        const passwordCheck = await bcrypt.compare(password, user.password)
        
        if(!passwordCheck){
            return NextResponse.json({err: "Nepareiza parole"}, { status: 400 })
        }

        const refreshToken = generateRefreshToken(user.id)

        const cookie = serialize("refresh-token", refreshToken, {
            httpOnly: true,
            secure: process.env.NODE_ENV === "production",
            maxAge: 60 * 60 * 24,
            path: "/" 
        })

        return NextResponse.json(user, {
            status: 200,
            headers: {
                "Set-Cookie": cookie
            }
        })
    },
    logout: async (req: NextRequest) => {
        const cookie = serialize("refresh-token", "", {
            httpOnly: true,
            secure: process.env.NODE_ENV === "production",
            maxAge: 60 * 60 * 24,
            path: "/" 
        })

        return NextResponse.json("Logged out", {
            status: 200,
            headers: {
                "Set-Cookie": cookie
            }
        })
    },
    loginCheck: async (req: NextRequest) => {
        const a = await auth(req)

        if(!a){
            return NextResponse.json({err: "Lietotājs netika atrasts"}, { status: 401 })
        }

        return NextResponse.json(a, { status: 200 })
    }
}