import path from "node:path";
import { fileURLToPath } from "node:url";
import dotenv from "dotenv";
import type { UserRole } from "./types.js";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const serverRoot = path.resolve(__dirname, "..");

dotenv.config({ path: path.resolve(serverRoot, "..", ".env") });
dotenv.config({ path: path.resolve(serverRoot, ".env") });

function fixedLoginRole(): UserRole {
  return process.env.FIXED_LOGIN_ROLE === "admin" ? "admin" : "user";
}

function envValue(name: string) {
  const value = process.env[name]?.trim();
  return value || undefined;
}

export const config = {
  host: envValue("HOST") ?? "0.0.0.0",
  port: Number(envValue("PORT") ?? 3001),
  jwtSecret: envValue("JWT_SECRET") ?? "dev-only-change-me",
  authMode: process.env.APP_AUTH_MODE === "fixed" ? "fixed" : "login",
  fixedLogin: {
    username: envValue("FIXED_LOGIN_USERNAME") ?? "viewer",
    role: fixedLoginRole()
  },
  allowUserEditSystemLibrary: envValue("ALLOW_USER_EDIT_SYSTEM_LIBRARY") === "true",
  dataDir: path.resolve(serverRoot, "data"),
  storageDir: path.resolve(serverRoot, "storage"),
  databasePath: envValue("DB_PATH") ?? path.resolve(serverRoot, "data", "model-library.db"),
  storageDriver: (envValue("STORAGE_DRIVER") ?? "local").toLowerCase(),
  publicBaseUrl: envValue("PUBLIC_BASE_URL") ?? "",
  cdnBaseUrl: envValue("CDN_BASE_URL") ?? "",
  cos: {
    secretId: envValue("COS_SECRET_ID") ?? "",
    secretKey: envValue("COS_SECRET_KEY") ?? "",
    bucket: envValue("COS_BUCKET") ?? "",
    region: envValue("COS_REGION") ?? "",
    prefix: (envValue("COS_PREFIX") ?? "").replace(/^\/+|\/+$/g, "")
  }
};
