import { getDb } from './db.js'
import { verifyPassword } from './password.js'

/**
 * Validate CoT auth: local users use password_hash; OIDC users use cot_password_hash (ATAK password).
 * @param {string} identifier - KestrelOS identifier (username)
 * @param {string} password - Plain password from CoT auth
 * @returns {Promise<boolean>} True if valid
 */
export async function validateCotAuth(identifier, password) {
  const id = typeof identifier === 'string' ? identifier.trim() : ''
  if (!id || typeof password !== 'string') return false

  const { get } = await getDb()
  const user = await get(
    'SELECT auth_provider, password_hash, cot_password_hash FROM users WHERE identifier = ?',
    [id],
  )
  if (!user) return false

  const hash = user.auth_provider === 'local' ? user.password_hash : user.cot_password_hash
  if (!hash) return false

  return verifyPassword(password, hash)
}
