import { fileURLToPath, URL } from "node:url";

import vue from "@vitejs/plugin-vue";
import { defineConfig, type Plugin } from "vite";

const root = fileURLToPath(new URL("..", import.meta.url));
const tasktreeApi = process.env.HWLAB_TASKTREE_NATIVE_API_URL ?? "http://127.0.0.1:6673";
const webHost = process.env.TASKTREE_NATIVE_WEB_HOST ?? "127.0.0.1";
const webPort = Number.parseInt(process.env.TASKTREE_NATIVE_WEB_PORT ?? "4173", 10);

const authPayload = {
  authenticated: true,
  mode: "server",
  authMethod: "native-web",
  identityAuthority: "hwlab-local",
  sessionKind: "browser",
  actor: { id: "usr_tasktree_native", username: "tasktree-native", role: "admin", status: "active" },
  capabilities: { web: "available", admin: "available" },
  access: { nav: { profileId: "tasktree-native", allowedIds: ["project.tasktree"], valuesRedacted: true } },
  expiresAt: null,
  valuesRedacted: true
};

function nativeAuth(): Plugin {
  return {
    name: "hwlab-tasktree-native-auth",
    configureServer(server) {
      server.middlewares.use((request, response, next) => {
        if (request.url === "/auth/logout") {
          response.writeHead(204, { "cache-control": "no-store" });
          response.end();
          return;
        }
        if (request.url !== "/auth/session" && request.url !== "/auth/bootstrap" && request.url !== "/auth/login") return next();
        response.writeHead(200, {
          "content-type": "application/json; charset=utf-8",
          "cache-control": "no-store",
          ...(request.url === "/auth/login" ? { "set-cookie": "hwlab_session=tasktree-native; Path=/; HttpOnly; SameSite=Lax" } : {})
        });
        response.end(JSON.stringify(authPayload));
      });
    }
  };
}

function nativeRuntimeConfig(): Plugin {
  return {
    name: "hwlab-tasktree-native-runtime-config",
    configureServer(server) {
      server.middlewares.use((request, response, next) => {
        if (request.url !== "/v1/web-performance" || request.method !== "POST") return next();
        response.writeHead(204, { "cache-control": "no-store" });
        response.end();
      });
    },
    transformIndexHtml() {
      return [{
        tag: "script",
        injectTo: "head-prepend",
        children: `window.HWLAB_CLOUD_WEB_CONFIG = {
          displayTime: { timeZone: "Asia/Shanghai", locale: "zh-CN", label: "北京时间" },
          workbench: {
            realtimeFeatures: { liveKafkaSse: false, kafkaRefreshReplay: false, projectionRealtime: true },
            debugCapabilities: { isolatedKafka: false, rawHwlabEventWindow: { enabled: false, maxEntries: 1, maxRetainedBytes: 1 } },
            traceTimeline: { autoExpandRunning: false, autoCollapseTerminal: false }
          }
        };`
      }];
    }
  };
}

export default defineConfig({
  root,
  plugins: [nativeRuntimeConfig(), nativeAuth(), vue()],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("../src", import.meta.url))
    }
  },
  server: {
    host: webHost,
    port: webPort,
    strictPort: true,
    watch: {
      usePolling: true,
      interval: 300,
      ignored: ["**/node_modules/**", "**/.git/**", "**/.state/**"]
    },
    proxy: {
      "/v1/tasktree": {
        target: tasktreeApi,
        changeOrigin: false
      }
    }
  }
});
