const assert = require("assert");
const fs = require("fs");
const path = require("path");
const { createWebAuth } = require("../src/services/web-auth");

function request({ hostname = "example.test", user = null, path = "/plugins/okf" } = {}) {
  return { hostname, path, session: { user }, get: () => hostname };
}

function response() {
  return {
    redirectedTo: null,
    redirect(target) { this.redirectedTo = target; return target; }
  };
}

const noPlatforms = createWebAuth({ getPlatformStatus: () => [] });
let res = response();
noPlatforms.requireAuth(request(), res, () => assert.fail("Anonymous request should not continue"));
assert.equal(res.redirectedTo, "/setup");

res = response();
noPlatforms.requireAuth(request({ hostname: "127.0.0.1" }), res, () => assert.fail("Anonymous request should not continue"));
assert.equal(res.redirectedTo, "/auth/localhost");

const discordAuth = createWebAuth({ getPlatformStatus: () => [{
  supported: true, enabled: true, configured: true, supportsLogin: true, loginPath: "/auth/discord"
}] });
res = response();
discordAuth.requireAuth(request(), res, () => assert.fail("Anonymous request should not continue"));
assert.equal(res.redirectedTo, "/auth/discord");

let continued = false;
discordAuth.requireAuth(request({ user: { id: "user-1" } }), response(), () => { continued = true; });
assert.equal(continued, true);

res = response();
noPlatforms.requireConfigured(request(), res, () => assert.fail("Unconfigured remote plugin request should not continue"));
assert.equal(res.redirectedTo, "/setup");

const root = path.join(__dirname, "..");
const okf = fs.readFileSync(path.join(root, "plugins", "okf", "index.js"), "utf8");
const server = fs.readFileSync(path.join(root, "src", "web", "server.js"), "utf8");
assert(okf.includes("const requireLogin = web.auth.requireAuth"));
assert.equal(okf.includes('res.redirect("/login")'), false);
assert(server.includes("app.use(mountPath, webAuth.requireConfigured, router)"));
console.log("Shared WebUI authentication verification passed: setup, localhost, configured provider, and OKF wiring.");
