import { Pool } from "pg";
const DEFAULT_PLAN = "free";
const DEFAULT_FLAGS = [];
const userDataCache = /* @__PURE__ */ new Map();
const CACHE_TTL = 5 * 60 * 1e3;
function getDatabasePool() {
  return new Pool({
    connectionString: process.env.DATABASE_URL,
    ssl: process.env.NODE_ENV === "production" ? { rejectUnauthorized: false } : false
  });
}
async function getUserPlanAndFlags(userId) {
  const cached = userDataCache.get(userId);
  if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
    return {
      plan: cached.plan,
      flags: cached.flags,
      cached: true
    };
  }
  try {
    const pool = getDatabasePool();
    const query = `
      SELECT
        "metaKey",
        "metaValue"
      FROM "users_metas"
      WHERE "userId" = $1
      AND "metaKey" IN ('user_plan', 'user_flags')
    `;
    const result = await pool.query(query, [userId]);
    let plan = DEFAULT_PLAN;
    let flags = DEFAULT_FLAGS;
    for (const row of result.rows) {
      if (row.metaKey === "user_plan") {
        const planValue = row.metaValue;
        if (typeof planValue === "string" && ["free", "starter", "premium"].includes(planValue)) {
          plan = planValue;
        }
      } else if (row.metaKey === "user_flags") {
        const flagsValue = row.metaValue;
        if (Array.isArray(flagsValue)) {
          const validFlags = flagsValue.filter(
            (flag) => typeof flag === "string" && ["beta_tester", "early_adopter", "limited_access", "vip", "restricted", "experimental"].includes(flag)
          );
          flags = validFlags;
        }
      }
    }
    userDataCache.set(userId, {
      plan,
      flags,
      timestamp: Date.now()
    });
    await pool.end();
    return {
      plan,
      flags,
      cached: false
    };
  } catch (error) {
    console.error("Failed to get user plan and flags:", error);
    return {
      plan: DEFAULT_PLAN,
      flags: DEFAULT_FLAGS,
      cached: false
    };
  }
}
async function updateUserPlan(userId, plan) {
  try {
    const pool = getDatabasePool();
    const query = `
      INSERT INTO "users_metas" ("userId", "metaKey", "metaValue", "dataType", "updatedAt")
      VALUES ($1, 'user_plan', $2, 'string', CURRENT_TIMESTAMP)
      ON CONFLICT ("userId", "metaKey")
      DO UPDATE SET
        "metaValue" = EXCLUDED."metaValue",
        "updatedAt" = CURRENT_TIMESTAMP
    `;
    await pool.query(query, [userId, plan]);
    await pool.end();
    userDataCache.delete(userId);
    return true;
  } catch (error) {
    console.error("Failed to update user plan:", error);
    return false;
  }
}
async function updateUserFlags(userId, flags) {
  try {
    const pool = getDatabasePool();
    const query = `
      INSERT INTO "users_metas" ("userId", "metaKey", "metaValue", "dataType", "updatedAt")
      VALUES ($1, 'user_flags', $2, 'json', CURRENT_TIMESTAMP)
      ON CONFLICT ("userId", "metaKey")
      DO UPDATE SET
        "metaValue" = EXCLUDED."metaValue",
        "updatedAt" = CURRENT_TIMESTAMP
    `;
    await pool.query(query, [userId, JSON.stringify(flags)]);
    await pool.end();
    userDataCache.delete(userId);
    return true;
  } catch (error) {
    console.error("Failed to update user flags:", error);
    return false;
  }
}
async function enrichUserWithPlanData(user) {
  const planData = await getUserPlanAndFlags(user.id);
  return {
    ...user,
    plan: planData.plan,
    flags: planData.flags
  };
}
export {
  enrichUserWithPlanData,
  getUserPlanAndFlags,
  updateUserFlags,
  updateUserPlan
};
