const { PrismaClient } = require('@prisma/client');
const crypto = require('crypto-js');

const prisma = new PrismaClient();

/**
 * Authentication service for the backend API
 */

/**
 * Response structure for login attempts
 */
interface LoginResponse {
  success: boolean;
  token?: string;
  error?: string;
  user?: {
    id: number;
    name: string;
    email: string;
    role: string;
  };
}

// Generate a secure token
const generateToken = (length = 64) => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let token = '';
  for (let i = 0; i < length; i++) {
    token += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return token;
};

/**
 * Authenticate user against the database
 */
async function authenticateUser(email, password) {
  try {
    // Hash the password using the same algorithm as the client
    const hashedPassword = crypto.SHA256(password).toString();
    
    // Find the user with matching email
    const user = await prisma.user.findUnique({
      where: { email }
    });
    
    // User not found
    if (!user) {
      return { 
        success: false, 
        error: 'User not found' 
      };
    }
    
    // Check if user is active
    if (!user.active) {
      return {
        success: false,
        error: 'Account is inactive'
      };
    }
    
    // Verify password
    if (user.password !== hashedPassword) {
      return { 
        success: false, 
        error: 'Invalid credentials' 
      };
    }
    
    // Generate authentication token
    const token = generateToken();
    
    // Update last login timestamp
    await prisma.user.update({
      where: { id: user.id },
      data: { lastLogin: new Date() }
    });
    
    // Return successful login response
    return {
      success: true,
      token,
      user: {
        id: user.id,
        name: `${user.name} ${user.surname}`,
        email: user.email,
        role: user.role
      }
    };
  } catch (error) {
    console.error('Authentication error:', error);
    return {
      success: false,
      error: 'An error occurred during authentication'
    };
  }
}

// Export using CommonJS syntax
module.exports = {
  authenticateUser
};