import { afterEach, describe, expect, test } from "bun:test"
import { Effect, Layer, Option } from "effect"
import { NodeFileSystem, NodePath } from "@effect/platform-node"
import path from "path"
import { hasIndexingPlugin } from "@saeeol/indexing/detect"
import { Account } from "../../../src/account/account"
import { Auth } from "../../../src/auth"
import { Config } from "../../../src/config/config"
import * as CrossSpawnSpawner from "@saeeol/core/cross-spawn-spawner"
import { Env } from "../../../src/env"
import { AppFileSystem } from "@saeeol/core/filesystem"
import { EffectFlock } from "@saeeol/core/util/effect-flock"
import { Filesystem } from "../../../src/util/filesystem"
import { Instance } from "../../../src/project/instance"
import { Npm } from "@saeeol/core/npm"
import { disposeAllInstances, tmpdir } from "../../fixture/fixture"

const infra = CrossSpawnSpawner.defaultLayer.pipe(
  Layer.provideMerge(Layer.mergeAll(NodeFileSystem.layer, NodePath.layer)),
)
const emptyAccount = Layer.mock(Account.Service)({
  active: () => Effect.succeed(Option.none()),
  activeOrg: () => Effect.succeed(Option.none()),
})
const emptyAuth = Layer.mock(Auth.Service)({
  all: () => Effect.succeed({}),
})
const noopNpm = Layer.mock(Npm.Service)({
  install: () => Effect.void,
  add: () => Effect.die("not implemented"),
  which: () => Effect.succeed(Option.none()),
})
const layer = Config.layer.pipe(
  Layer.provide(EffectFlock.defaultLayer),
  Layer.provide(AppFileSystem.defaultLayer),
  Layer.provide(Env.defaultLayer),
  Layer.provide(emptyAuth),
  Layer.provide(emptyAccount),
  Layer.provideMerge(infra),
  Layer.provide(noopNpm),
)

const load = () => Effect.runPromise(Config.Service.use((svc) => svc.get()).pipe(Effect.scoped, Effect.provide(layer)))
const clear = (wait = false) =>
  Effect.runPromise(Config.Service.use((svc) => svc.invalidate(wait)).pipe(Effect.scoped, Effect.provide(layer)))

describe("saeeol default indexing plugin", () => {
  afterEach(async () => {
    await disposeAllInstances()
    await clear(true)
  })

  test("does not hard-enable indexing plugin when default plugins are disabled", async () => {
    const prev = process.env["SAEEOL_DISABLE_DEFAULT_PLUGINS"]
    process.env["SAEEOL_DISABLE_DEFAULT_PLUGINS"] = "true"

    try {
      await using tmp = await tmpdir({
        init: async (dir) => {
          await Filesystem.write(
            path.join(dir, "saeeol.json"),
            JSON.stringify({
              $schema: "https://app.saeeol.ai/config.json",
              plugin: ["global-plugin-1"],
            }),
          )
        },
      })

      await Instance.provide({
        directory: tmp.path,
        fn: async () => {
          const config = await load()
          expect(hasIndexingPlugin(config.plugin ?? [])).toBe(false)
        },
      })
    } finally {
      if (prev === undefined) delete process.env["SAEEOL_DISABLE_DEFAULT_PLUGINS"]
      else process.env["SAEEOL_DISABLE_DEFAULT_PLUGINS"] = prev
    }
  })
})
