// services/authService.js
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { v4: uuidv4 } = require('uuid');
const { User } = require('../models'); // Assuming we have a User model

const JWT_SECRET = process.env.JWT_SECRET || 'fallback_secret';

// Mock database - in real implementation, this would be a real database
const users = [];

const login = async (email, password) => {
  try {
    // Find user by email
    const user = users.find(u => u.email === email);
    
    if (!user) {
      return { error: 'Invalid email or password' };
    }
    
    // Check password
    const isPasswordValid = await bcrypt.compare(password, user.passwordHash);
    
    if (!isPasswordValid) {
      return { error: 'Invalid email or password' };
    }
    
    // Generate JWT token
    const token = jwt.sign(
      { userId: user.id, email: user.email, tenantId: user.tenantId },
      JWT_SECRET,
      { expiresIn: '24h' }
    );
    
    // Return user info and token (excluding password)
    return {
      user: {
        id: user.id,
        email: user.email,
        firstName: user.firstName,
        lastName: user.lastName,
        userType: user.userType,
        tenantId: user.tenantId
      },
      token
    };
  } catch (error) {
    console.error('Login service error:', error);
    return { error: 'Internal server error' };
  }
};

const register = async (email, password, firstName, lastName, userType, tenantId) => {
  try {
    // Check if user already exists
    const existingUser = users.find(u => u.email === email);
    
    if (existingUser) {
      return { error: 'User with this email already exists' };
    }
    
    // Validate user type
    if (!['job-seeker', 'job-provider'].includes(userType)) {
      return { error: 'User type must be either job-seeker or job-provider' };
    }
    
    // Hash password
    const saltRounds = 12;
    const passwordHash = await bcrypt.hash(password, saltRounds);
    
    // Create new user
    const newUser = {
      id: uuidv4(),
      email,
      passwordHash,
      firstName,
      lastName,
      userType,
      tenantId,
      createdAt: new Date(),
      updatedAt: new Date()
    };
    
    users.push(newUser);
    
    // Return user info (excluding password)
    return {
      user: {
        id: newUser.id,
        email: newUser.email,
        firstName: newUser.firstName,
        lastName: newUser.lastName,
        userType: newUser.userType,
        tenantId: newUser.tenantId
      }
    };
  } catch (error) {
    console.error('Registration service error:', error);
    return { error: 'Internal server error' };
  }
};

module.exports = {
  login,
  register
};