import { db, id, now, visibleClause } from '../db.js';
import { encryptSecret } from '../services/cryptoStore.js';
import { camelCredential } from './mappers.js';

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

export function createCredential(payload, userId) {
  const encrypted = encryptSecret(payload.secret);
  const credentialId = id('cred');
  db.prepare(`
    INSERT INTO credentials
    (id, name, kind, username, secret_cipher, secret_iv, secret_tag, visibility, owner_user_id, group_id, created_by, created_at, updated_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `).run(
    credentialId,
    payload.name,
    payload.kind,
    payload.username || '',
    encrypted.cipher,
    encrypted.iv,
    encrypted.tag,
    payload.visibility,
    userId,
    payload.visibility === 'group' ? payload.groupId || null : null,
    userId,
    now(),
    now()
  );
  return camelCredential(db.prepare('SELECT * FROM credentials WHERE id = ?').get(credentialId));
}

export function updateCredential(credentialId, payload, userId) {
  const existing = db.prepare(`SELECT * FROM credentials WHERE id = ? AND ${visibleClause()}`).get(credentialId, userId, userId);
  if (!existing) return null;
  const encrypted = payload.secret ? encryptSecret(payload.secret) : {
    cipher: existing.secret_cipher,
    iv: existing.secret_iv,
    tag: existing.secret_tag
  };
  const visibility = payload.visibility || existing.visibility;
  db.prepare(`
    UPDATE credentials
    SET name = ?, kind = ?, username = ?, secret_cipher = ?, secret_iv = ?, secret_tag = ?,
        visibility = ?, group_id = ?, updated_at = ?
    WHERE id = ?
  `).run(
    payload.name || existing.name,
    payload.kind || existing.kind,
    payload.username ?? existing.username,
    encrypted.cipher,
    encrypted.iv,
    encrypted.tag,
    visibility,
    visibility === 'group' ? payload.groupId || existing.group_id : null,
    now(),
    credentialId
  );
  return camelCredential(db.prepare('SELECT * FROM credentials WHERE id = ?').get(credentialId));
}

export function deleteCredential(credentialId, userId) {
  db.prepare(`DELETE FROM credentials WHERE id = ? AND ${visibleClause()}`).run(credentialId, userId, userId);
}
