import pool from '@/lib/database';
import type { RowDataPacket } from 'mysql2';

import bcrypt from 'bcrypt';

import { NextResponse, NextRequest } from 'next/server';
import { cookies } from 'next/headers'

export async function POST(request: NextRequest) {
    // body取得
    const body = await request.json();
    const { email, password } = body;

    // ユーザー取得
    const [existingUsers] = await pool.execute<RowDataPacket[]>(
        "SELECT * FROM users WHERE email = ?", [email]
    );

    // ユーザーが存在しない場合
    if (existingUsers.length === 0) {
        return NextResponse.json({
            status: "error",
            error: "User not found"
        }, { status: 404 });
    }

    const user = existingUsers[0];
    const passwordMatch = await bcrypt.compare(password, user.password);

    // パスワード確認
    if (!passwordMatch) {
        return NextResponse.json({
            status: "error",
            error: "Incorrect password"
        }, { status: 401 });
    } else {
        // 成功
        const sessionCookie = await cookies();
        sessionCookie.set('user', user.id);
        sessionCookie.set('password', password);

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