import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
import type { Employee } from './types';

async function getEmployeeByIdRuntime(employeeId: string): Promise<Employee | undefined> {
  const normalizedId = String(employeeId || '').trim();
  if (!normalizedId) return undefined;

  try {
    const { pgGetEmployeeById } = await import('./postgres/data-access');
    const employee = await pgGetEmployeeById(normalizedId);
    if (employee) return employee as Employee;
  } catch {
    // Fall back to legacy JSON runtime if Postgres lookup fails.
  }

  const legacyData = await import('./data');
  return legacyData.getEmployeeById(normalizedId);
}

const SESSION_COOKIE_NAME = 'staff_track_session';
const LONG_TERM_COOKIE_AGE = 60 * 60 * 24 * 30; // 30 days

export async function createSession(userId: string, rememberMe: boolean = false) {
  const cookieStore = await cookies();
  const options: {
    httpOnly: true;
    secure: boolean;
    path: '/';
    maxAge?: number;
  } = {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    path: '/',
  };

  if (rememberMe) {
    options.maxAge = LONG_TERM_COOKIE_AGE;
  }

  cookieStore.set(SESSION_COOKIE_NAME, userId, options);
}

export async function getSession(): Promise<{ user: Omit<Employee, 'password'> | null }> {
  const cookieStore = await cookies();
  const sessionId = cookieStore.get(SESSION_COOKIE_NAME)?.value;
  
  if (!sessionId) {
    return { user: null };
  }
  
  const user = await getEmployeeByIdRuntime(sessionId);

  if (user) {
    const { password, ...userWithoutPassword } = user;
    return { user: userWithoutPassword };
  }
  
  return { user: null };
}

export async function destroySession() {
  const cookieStore = await cookies();
  cookieStore.set(SESSION_COOKIE_NAME, '', { expires: new Date(0), path: '/' });
}

export async function verifySession() {
    const session = await getSession();
    if (!session?.user) {
      redirect('/login');
    }
    return session;
}
