import { db } from '../../config/secureDatabase'
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
import { FieldEncryption } from '../../services/encryption'
import { User, LoginResponse } from '@skillmate/shared'

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production'

export async function loginUser(identifier: string, password: string): Promise<LoginResponse> {
  let userRow: any
  if (identifier.includes('@')) {
    const emailHash = FieldEncryption.hash(identifier)
    userRow = db.prepare(`
      SELECT id, username, email, password, role, employee_id, last_login, is_active, created_at, updated_at
      FROM users
      WHERE email_hash = ? AND is_active = 1
    `).get(emailHash)
  } else {
    userRow = db.prepare(`
      SELECT id, username, email, password, role, employee_id, last_login, is_active, created_at, updated_at
      FROM users
      WHERE username = ? AND is_active = 1
    `).get(identifier)
  }

  if (!userRow) {
    const e: any = new Error('Invalid credentials')
    e.statusCode = 401
    throw e
  }

  const isValidPassword = await bcrypt.compare(password, userRow.password)
  if (!isValidPassword) {
    const e: any = new Error('Invalid credentials')
    e.statusCode = 401
    throw e
  }

  const now = new Date().toISOString()
  db.prepare('UPDATE users SET last_login = ? WHERE id = ?').run(now, userRow.id)

  const user: User = {
    id: userRow.id,
    username: userRow.username,
    email: FieldEncryption.decrypt(userRow.email) || '',
    role: userRow.role,
    employeeId: userRow.employee_id,
    lastLogin: new Date(now),
    isActive: Boolean(userRow.is_active),
    createdAt: new Date(userRow.created_at),
    updatedAt: new Date(userRow.updated_at)
  }

  const token = jwt.sign(
    { user },
    JWT_SECRET,
    { expiresIn: '24h' }
  )

  return {
    user,
    token: {
      accessToken: token,
      expiresIn: 86400,
      tokenType: 'Bearer'
    }
  }
}

