import { v4 as uuidv4 } from "uuid";
import { getAdapter } from "../driver.js";

function rowToKey(row) {
  if (!row) return null;
  return {
    id: row.id,
    key: row.key,
    name: row.name,
    machineId: row.machineId,
    userId: row.userId,
    comment: row.comment ?? "",
    isActive: row.isActive === 1 || row.isActive === true,
    createdAt: row.createdAt,
    rtkEnabled: row.rtkEnabled === null || row.rtkEnabled === undefined ? null : (row.rtkEnabled === 1 || row.rtkEnabled === true),
    cavemanEnabled: row.cavemanEnabled === null || row.cavemanEnabled === undefined ? null : (row.cavemanEnabled === 1 || row.cavemanEnabled === true),
    cavemanLevel: row.cavemanLevel ?? null,
  };
}

export async function getApiKeys() {
  const db = await getAdapter();
  const rows = await db.all(`SELECT * FROM apiKeys ORDER BY createdAt ASC`);
  return rows.map(rowToKey);
}

export async function getApiKeyById(id) {
  const db = await getAdapter();
  const row = await db.get(`SELECT * FROM apiKeys WHERE id = ?`, [id]);
  return rowToKey(row);
}

export async function findByUserId(userId) {
  const db = await getAdapter();
  const rows = await db.all(`SELECT * FROM apiKeys WHERE userId = ? ORDER BY createdAt ASC`, [userId]);
  return rows.map(rowToKey);
}

export async function findByIdAndUserId(id, userId) {
  const db = await getAdapter();
  const row = await db.get(`SELECT * FROM apiKeys WHERE id = ? AND userId = ?`, [id, userId]);
  return rowToKey(row);
}

export async function createApiKey(name, userId, machineId, comment = "", options = {}) {
  if (!userId) throw new Error("userId is required");
  if (!machineId) throw new Error("machineId is required");
  const db = await getAdapter();
  const { generateApiKeyWithMachine } = await import("@/shared/utils/apiKey");
  const result = generateApiKeyWithMachine(machineId);
  const apiKey = {
    id: uuidv4(),
    name,
    key: result.key,
    machineId,
    userId,
    comment,
    isActive: true,
    createdAt: new Date().toISOString(),
    rtkEnabled: options.rtkEnabled ?? false,
    cavemanEnabled: options.cavemanEnabled ?? false,
    cavemanLevel: options.cavemanLevel ?? null,
  };
  await db.run(
    `INSERT INTO apiKeys(id, key, name, machineId, userId, comment, isActive, createdAt, rtkEnabled, cavemanEnabled, cavemanLevel) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
    [apiKey.id, apiKey.key, apiKey.name, apiKey.machineId, apiKey.userId, apiKey.comment, 1, apiKey.createdAt, apiKey.rtkEnabled ? 1 : 0, apiKey.cavemanEnabled ? 1 : 0, apiKey.cavemanLevel]
  );
  return apiKey;
}

export async function updateApiKey(id, data) {
  const db = await getAdapter();
  let result = null;
  await db.transaction(async () => {
    const row = await db.get(`SELECT * FROM apiKeys WHERE id = ?`, [id]);
    if (!row) return;
    const merged = { ...rowToKey(row), ...data };
    await db.run(
      `UPDATE apiKeys SET key = ?, name = ?, machineId = ?, userId = ?, comment = ?, isActive = ?, rtkEnabled = ?, cavemanEnabled = ?, cavemanLevel = ? WHERE id = ?`,
      [merged.key, merged.name, merged.machineId, merged.userId, merged.comment ?? "", merged.isActive ? 1 : 0, merged.rtkEnabled === null || merged.rtkEnabled === undefined ? null : (merged.rtkEnabled ? 1 : 0), merged.cavemanEnabled === null || merged.cavemanEnabled === undefined ? null : (merged.cavemanEnabled ? 1 : 0), merged.cavemanLevel ?? null, id]
    );
    result = merged;
  });
  return result;
}

export async function deleteApiKey(id) {
  const db = await getAdapter();
  const res = await db.run(`DELETE FROM apiKeys WHERE id = ?`, [id]);
  return (res?.changes ?? 0) > 0;
}

export async function deleteApiKeyForUser(id, userId) {
  const db = await getAdapter();
  const res = await db.run(`DELETE FROM apiKeys WHERE id = ? AND userId = ?`, [id, userId]);
  return (res?.changes ?? 0) > 0;
}

export async function validateApiKey(key) {
  const db = await getAdapter();
  const row = await db.get(`SELECT isActive FROM apiKeys WHERE key = ?`, [key]);
  if (!row) return false;
  return row.isActive === 1 || row.isActive === true;
}

export async function getApiKeyWithSettings(key) {
  const db = await getAdapter();
  const row = await db.get(`SELECT * FROM apiKeys WHERE key = ?`, [key]);
  return rowToKey(row);
}
