'use server';

import { redirect } from 'next/navigation';
import { cookies, headers } from 'next/headers';
import { verifyPassword, createSession } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { rateLimit, clientIpFromHeaders } from '@/lib/rateLimit';

export async function loginAction(email: string, password: string) {
  try {
    // Per-IP cap: 10 login attempts per 15 minutes. Slows credential
    // stuffing without locking out legitimate typo-prone users.
    const hdrs = await headers();
    const ip = clientIpFromHeaders(hdrs);
    const limit = rateLimit(`login:${ip}`, { limit: 10, windowMs: 15 * 60_000 });
    if (!limit.ok) {
      return {
        error: `Too many login attempts. Try again in ${limit.retryAfterSec}s.`,
      };
    }

    // Look up user by email
    const user = await prisma.user.findUnique({
      where: { email },
    });

    if (!user) {
      return { error: 'Invalid email or password' };
    }

    // Verify the password
    const isValid = await verifyPassword(password, user.passwordHash);

    if (!isValid) {
      return { error: 'Invalid email or password' };
    }

    // Create a session
    const session = await createSession(user.id);

    // Set the session cookie
    const cookieStore = await cookies();
    cookieStore.set('sessionToken', session.token, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 60 * 60 * 24 * 30, // 30 days
      path: '/',
    });

    return { success: true };
  } catch (error) {
    console.error('Login error:', error);
    return { error: 'An error occurred during login' };
  }
}

export async function redirectToDashboard() {
  redirect('/main/dashboard');
}
