import { Router } from "express";
import { nanoid } from "nanoid";
import { DEFAULT_PROMPT_VERSION } from "../config";
import { listBuiltinPromptPresets } from "../services/promptBuilder";
import { listPresets, savePreset } from "../services/traceLogger";
import type { PromptPreset } from "../types/preset";
import { created, ok } from "../utils/http";

export function buildPresetsRouter(): Router {
  const router = Router();

  router.get("/api/presets", (_req, res) => {
    const stored = listPresets();
    const builtin = listBuiltinPromptPresets();
    const combined = [...builtin, ...stored];
    ok(res, {
      ok: true,
      default_prompt_version: DEFAULT_PROMPT_VERSION,
      presets: combined
    });
  });

  router.post("/api/presets/save", (req, res, next) => {
    try {
      const body = (req.body ?? {}) as Partial<PromptPreset>;
      const now = new Date().toISOString();
      const preset: PromptPreset = {
        id: body.id ?? `preset-${nanoid(8)}`,
        name: body.name ?? "Пользовательский пресет",
        createdAt: body.createdAt ?? now,
        updatedAt: now,
        prompt_version: body.prompt_version ?? DEFAULT_PROMPT_VERSION,
        systemPrompt: body.systemPrompt ?? "",
        developerPrompt: body.developerPrompt ?? "",
        domainPrompt: body.domainPrompt ?? "",
        schemaNotes: body.schemaNotes ?? "",
        fewShotExamples: body.fewShotExamples ?? ""
      };
      savePreset(preset);
      created(res, {
        ok: true,
        preset
      });
    } catch (error) {
      next(error);
    }
  });

  return router;
}
