import { config as loadDotenv } from "dotenv";
import { existsSync } from "node:fs";
import path from "node:path";

// Ladda .env från paketet ELLER monorepo-roten (pnpm --filter sätter cwd till paketet).
for (const candidate of [".env", "../.env", "../../.env"]) {
  const p = path.resolve(process.cwd(), candidate);
  if (existsSync(p)) {
    loadDotenv({ path: p });
    break;
  }
}
import { createHmac } from "node:crypto";
import { createDatabase, type Database } from "@app/database";
import { createAamosClient, type AamosClient } from "@app/ai-contracts";

export interface WorkerContext {
  db: Database;
  aamos: AamosClient;
  /** Bygger läs-URL för lagrade bilder (samma signaturlogik som API:ts mock-S3). */
  readUrl: (key: string) => string;
  apiBaseUrl: string;
  close: () => Promise<void>;
}

export function createContext(): WorkerContext {
  const { db, pool } = createDatabase();
  const aamos = createAamosClient();
  const apiBaseUrl = process.env.API_BASE_URL ?? "http://localhost:4000";
  const secret = process.env.ENTITLEMENT_SIGNING_SECRET ?? "dev-only-change-me-three";

  return {
    db,
    aamos,
    apiBaseUrl,
    readUrl: (key: string) => {
      const sig = createHmac("sha256", secret).update(key).digest("hex").slice(0, 32);
      return `${apiBaseUrl}/v1/mock-s3/${encodeURIComponent(key)}?sig=${sig}`;
    },
    close: async () => {
      await pool.end();
    },
  };
}
