import { db, id, now, visibleClause } from '../db.js';
import { vcenterConnectionSchema } from '../forms/schemas.js';
import { decryptSecret, encryptSecret } from '../services/cryptoStore.js';
import { camelVCenterConnection } from './mappers.js';

function normalizeConnection(body, existing = {}) {
  const parsed = vcenterConnectionSchema.parse({
    ...existing,
    ...body,
    password: body.password || ''
  });
  const targetType = parsed.targetType || 'vcenter';
  const apiMode = targetType === 'host'
    ? 'web-services'
    : (parsed.apiMode === 'web-services' ? 'auto' : parsed.apiMode);
  return {
    ...parsed,
    targetType,
    apiMode,
    baseUrl: String(parsed.baseUrl || '').trim().replace(/\/+$/, ''),
    groupId: parsed.visibility === 'group' ? parsed.groupId || null : null
  };
}

export function listVCenterConnections(userId) {
  return db.prepare(`
    SELECT c.*, g.name AS group_name
    FROM vcenter_connections c
    LEFT JOIN groups g ON g.id = c.group_id
    WHERE ${visibleClause('c')}
    ORDER BY c.name
  `).all(userId, userId).map(camelVCenterConnection);
}

export function getVCenterConnection(connectionId, userId, includeSecret = false) {
  if (!connectionId) return null;
  const row = db.prepare(`
    SELECT c.*, g.name AS group_name
    FROM vcenter_connections c
    LEFT JOIN groups g ON g.id = c.group_id
    WHERE c.id = ? AND ${visibleClause('c')}
  `).get(connectionId, userId, userId);
  if (!row) return null;
  return includeSecret ? { ...row, password: decryptSecret(row) } : camelVCenterConnection(row);
}

export function getVCenterConnectionSystem(connectionId, includeSecret = false) {
  if (!connectionId) return null;
  const row = db.prepare('SELECT * FROM vcenter_connections WHERE id = ?').get(connectionId);
  if (!row) return null;
  return includeSecret ? { ...row, password: decryptSecret(row) } : camelVCenterConnection(row);
}

export function createVCenterConnection(body, userId) {
  const payload = normalizeConnection(body);
  const encrypted = encryptSecret(payload.password);
  const connectionId = id('vc');
  db.prepare(`
    INSERT INTO vcenter_connections (
      id, name, base_url, username, secret_cipher, secret_iv, secret_tag,
      target_type, api_mode, request_timeout_ms, allow_untrusted_tls, enabled,
      visibility, owner_user_id, group_id, created_by, created_at, updated_at
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `).run(
    connectionId,
    payload.name,
    payload.baseUrl,
    payload.username,
    encrypted.cipher,
    encrypted.iv,
    encrypted.tag,
    payload.targetType,
    payload.apiMode,
    payload.requestTimeoutMs,
    payload.allowUntrustedTls ? 1 : 0,
    payload.enabled ? 1 : 0,
    payload.visibility,
    userId,
    payload.groupId,
    userId,
    now(),
    now()
  );
  return getVCenterConnection(connectionId, userId);
}

export function updateVCenterConnection(connectionId, body, userId) {
  const existing = getVCenterConnection(connectionId, userId, true);
  if (!existing) return null;
  const payload = normalizeConnection(body, {
    name: existing.name,
    baseUrl: existing.base_url,
    username: existing.username,
    targetType: existing.target_type || 'vcenter',
    apiMode: existing.api_mode,
    requestTimeoutMs: existing.request_timeout_ms,
    allowUntrustedTls: Boolean(existing.allow_untrusted_tls),
    enabled: Boolean(existing.enabled),
    visibility: existing.visibility,
    groupId: existing.group_id
  });
  const encrypted = payload.password ? encryptSecret(payload.password) : {
    cipher: existing.secret_cipher,
    iv: existing.secret_iv,
    tag: existing.secret_tag
  };
  db.prepare(`
    UPDATE vcenter_connections
    SET name = ?, base_url = ?, username = ?, secret_cipher = ?, secret_iv = ?, secret_tag = ?,
        target_type = ?, api_mode = ?, request_timeout_ms = ?, allow_untrusted_tls = ?, enabled = ?,
        visibility = ?, group_id = ?, updated_at = ?
    WHERE id = ?
  `).run(
    payload.name,
    payload.baseUrl,
    payload.username,
    encrypted.cipher,
    encrypted.iv,
    encrypted.tag,
    payload.targetType,
    payload.apiMode,
    payload.requestTimeoutMs,
    payload.allowUntrustedTls ? 1 : 0,
    payload.enabled ? 1 : 0,
    payload.visibility,
    payload.groupId,
    now(),
    connectionId
  );
  return getVCenterConnection(connectionId, userId);
}

export function deleteVCenterConnection(connectionId, userId) {
  db.prepare(`DELETE FROM vcenter_connections WHERE id = ? AND ${visibleClause()}`).run(connectionId, userId, userId);
}

export function recordVCenterConnectionTest(connectionId, status, message) {
  db.prepare(`
    UPDATE vcenter_connections
    SET last_test_status = ?, last_test_message = ?, last_test_at = ?, updated_at = ?
    WHERE id = ?
  `).run(status, message || '', now(), now(), connectionId);
}
