const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

const AUTH_FILE = path.join(__dirname, '..', '..', 'frontend', '.auth.json');

let authData = null;

async function initAuth(fileConfig) {
  if (fs.existsSync(AUTH_FILE)) {
    authData = JSON.parse(fs.readFileSync(AUTH_FILE, 'utf8'));
    console.log('[Auth] Loaded existing credentials for user:', authData.username);
  } else {
    const username = fileConfig.CFG_WEBUI_USERNAME || 'admin';
    const password = fileConfig.CFG_WEBUI_PASSWORD || 'changeme';
    console.log('[Auth] Creating auth credentials for user:', username);
    const passwordHash = await bcrypt.hash(password, 12);
    const jwtSecret = crypto.randomBytes(32).toString('hex');
    authData = { username, passwordHash, jwtSecret };
    fs.writeFileSync(AUTH_FILE, JSON.stringify(authData, null, 2), 'utf8');
  }
}

function generateToken(username) {
  return jwt.sign({ sub: username }, authData.jwtSecret, { expiresIn: '30d' });
}

function verifyToken(token) {
  try {
    return jwt.verify(token, authData.jwtSecret);
  } catch {
    return null;
  }
}

async function verifyPassword(plain, hash) {
  return bcrypt.compare(plain, hash);
}

function getCredentials() {
  return authData;
}

module.exports = { initAuth, generateToken, verifyToken, verifyPassword, getCredentials };
