import { db } from '../config/secureDatabase'
import bcrypt from 'bcryptjs'
import { FieldEncryption } from '../services/encryption'

export async function createUserUC(input: { username: string; email: string; password: string; role: string; employeeId?: string | null }, actorRole: string) {
  const assignedRole = (actorRole === 'admin') ? input.role : 'user'
  const existingUser = db.prepare('SELECT id FROM users WHERE username = ?').get(input.username)
  if (existingUser) {
    const e: any = new Error('Username already exists')
    e.statusCode = 409
    throw e
  }
  const emailHash = FieldEncryption.hash(input.email)
  const existingEmail = db.prepare('SELECT id FROM users WHERE email_hash = ?').get(emailHash)
  if (existingEmail) {
    const e: any = new Error('Email already exists')
    e.statusCode = 409
    throw e
  }
  const hashedPassword = bcrypt.hashSync(input.password, 12)
  const now = new Date().toISOString()
  const { v4: uuidv4 } = await import('uuid')
  const userId = uuidv4()
  db.prepare(`
    INSERT INTO users (id, username, email, email_hash, password, role, employee_id, is_active, created_at, updated_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `).run(
    userId,
    input.username,
    FieldEncryption.encrypt(input.email),
    emailHash,
    hashedPassword,
    assignedRole,
    input.employeeId || null,
    1,
    now,
    now
  )
  return { id: userId, role: assignedRole }
}

export function updateUserRoleUC(id: string, role: 'admin' | 'superuser' | 'user') {
  db.prepare(`
    UPDATE users SET role = ?, updated_at = ?
    WHERE id = ?
  `).run(role, new Date().toISOString(), id)
}

