import { defineConfig, type Plugin } from 'vite';
import { exchangeHiveCastActorCredential } from '@open-matrix/sdk';

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

function requiredEnv(name: string): string {
  const value = env(name);
  if (!value) throw new Error(`${name}_REQUIRED`);
  return value;
}

function sendJson(res: { statusCode: number; setHeader(name: string, value: string): void; end(body: string): void }, status: number, body: unknown): void {
  const text = JSON.stringify(body);
  res.statusCode = status;
  res.setHeader('content-type', 'application/json');
  res.end(text);
}

function hiveCastActorCredentialPlugin(): Plugin {
  return {
    name: 'fresh-hivecast-actor-credential',
    configureServer(server) {
      server.middlewares.use('/matrix/actor-credential', async (req, res) => {
        if (req.method !== 'POST') {
          sendJson(res, 405, { ok: false, error: 'Method not allowed' });
          return;
        }
        try {
          const credential = await exchangeHiveCastActorCredential({
            cloud: requiredEnv('MATRIX_CLOUD'),
            apiKey: requiredEnv('MATRIX_API_KEY'),
            space: requiredEnv('MATRIX_SPACE'),
          }, {
            mount: env('MATRIX_WEB_MOUNT') ?? 'fresh.web.echo',
            actorId: 'FreshBrowserEchoActor',
            packageId: 'matrix-sdk-demo-fresh-web-page',
            runtimeId: `fresh-web-${process.pid}`,
            accepts: { echo: {}, getStatus: {} },
            ttlSeconds: 300,
          });
          sendJson(res, 200, credential);
        } catch (error) {
          sendJson(res, 500, {
            ok: false,
            error: error instanceof Error ? error.message : String(error),
          });
        }
      });
    },
  };
}

export default defineConfig({
  plugins: [hiveCastActorCredentialPlugin()],
});
