import { NextRequest, NextResponse } from "next/server";
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import prisma from "@/app/prisma";

interface Body {
    email: string;
    password: string;
    remember?: boolean;
}

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

        if (!body.email || !body.password) {
            return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
        }

        const user = await prisma.user.findUnique({
            where: {
                email: body.email,
            },
        });

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

        const validPassword = await bcrypt.compare(body.password, user.password);

        if (!validPassword) {
            return NextResponse.json({ error: "Invalid password" }, { status: 401 });
        }

        if(!process.env.JWT_SECRET) {
            return NextResponse.json({ error: "No JWT secret found" }, { status: 500 });
        }

        const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: body.remember ? "7d" : "1h" });

        const lastLogin = new Date();

        await prisma.user.update({
            where: {
                id: user.id,
            },
            data: {
                lastLogin,
            },
        });

        return NextResponse.json({ message: "Login successful", token }, { status: 200 });

    } catch (error: any) {
        return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
    }
}
