// // Login route. The route handler is intentionally tiny: validate input,
// // call the service, set the cookie. All decisions about credentials
// // live in authService.

// import { NextRequest } from 'next/server';
// import { cookies } from 'next/headers';
// import { apiHandler, ok } from '@/lib/utils/api';
// import { authService } from '@/lib/services/auth.service';
// import { loginSchema } from '@/lib/validators';
// import { AUTH_COOKIE } from '@/lib/auth/session';

// export async function POST(req: NextRequest) {
//   return apiHandler(async () => {
//     const body = await req.json();
//     const input = loginSchema.parse(body);
//     const { token, user } = await authService.login(input);

//     cookies().set(AUTH_COOKIE, token, {
//       httpOnly: true,
//       sameSite: 'lax',
//       secure: process.env.NODE_ENV === 'production',
//       path: '/',
//       // 7 days in seconds, matches JWT_EXPIRES_IN default
//       maxAge: 60 * 60 * 24 * 7,
//     });

//     return ok({ user });
//   });
// }

import { NextRequest, NextResponse } from 'next/server';
import { authService } from '@/lib/services/auth.service';
import { loginSchema } from '@/lib/validators';
import { AUTH_COOKIE } from '@/lib/auth/session';

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const input = loginSchema.parse(body);

    const { token, user } = await authService.login(input);

    const res = NextResponse.json({
      success: true,
      user,
    });

    res.cookies.set(AUTH_COOKIE, token, {
      httpOnly: true,
      sameSite: 'lax',
      secure: process.env.NODE_ENV === 'production',
      path: '/',
      maxAge: 60 * 60 * 24 * 7,
    });

    return res;
  } catch (err: any) {
    console.error("LOGIN ERROR:", err);

    return NextResponse.json(
      {
        success: false,
        message: err?.message || "Internal Server Error",
      },
      { status: 500 }
    );
  }
}