import { NextRequest, NextResponse } from "next/server";

interface LoginRequest {
  email: string;
  password: string;
  rememberMe: boolean;
}

// Mock user storage for demonstration
const mockUsers: {
  [key: string]: {
    id: string;
    firstName: string;
    lastName: string;
    email: string;
    password: string;
    userType: "student" | "teacher";
  };
} = {
  "demo@example.com": {
    id: "user_1",    firstName: "Demo",    lastName: "User",    email: "demo@example.com",    password: "DemoPassword123", // Demo password
    userType: "student"},
  "teacher@example.com": {
    id: "user_2",    firstName: "Demo",    lastName: "Teacher",    email: "teacher@example.com",    password: "TeacherPassword123",    userType: "teacher"},
};

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

    // Validate input
    if (!body.email || !body.password) {
      return NextResponse.json(
        { message: "E-posta ve şifre gereklidir" },
        { status: 400 }
      );
    }

    // Find user
    const user = mockUsers[body.email];

    if (!user) {
      return NextResponse.json(
        { message: "E-posta veya şifre hatalı" },
        { status: 401 }
      );
    }

    // In production, use bcrypt.compare()
    // const passwordMatch = await bcrypt.compare(body.password, user.password);

    if (user.password !== body.password) {
      return NextResponse.json(
        { message: "E-posta veya şifre hatalı" },
        { status: 401 }
      );
    }

    // Create response with user data
    const response = NextResponse.json(
      {
        message: "Giriş başarıyla gerçekleştirildi",        user: {
          id: user.id,
          firstName: user.firstName,
          lastName: user.lastName,
          email: user.email,
          userType: user.userType,
        },
      },
      { status: 200 }
    );

    // In production, set secure HTTP-only cookies
    if (body.rememberMe) {
      // Set longer expiration for "remember me"
      response.cookies.set("authToken", `token_${user.id}`, {
        maxAge: 30 * 24 * 60 * 60, // 30 days
        httpOnly: true,
        secure: process.env.NODE_ENV === "production",        sameSite: "lax"});
    } else {
      response.cookies.set("authToken", `token_${user.id}`, {
        maxAge: 24 * 60 * 60, // 24 hours
        httpOnly: true,
        secure: process.env.NODE_ENV === "production",        sameSite: "lax"});
    }

    return response;
  } catch (error) {
    console.error("Login error:", error);
    return NextResponse.json(
      { message: "Sunucu hatası oluştu" },
      { status: 500 }
    );
  }
}
