import { Router } from "express";
import Database from "better-sqlite3";
import { startPreview, stopPreview, updatePreviewConfig } from "../services/previewService";

export function previewRouter(db: Database.Database, storageDir: string): Router {
  const router = Router();

  // POST /api/v1/creatives/:id/preview/start
  router.post("/creatives/:id/preview/start", async (req, res) => {
    try {
      const creativeId = req.params.id as string;

      const creative = db
        .prepare("SELECT * FROM creatives WHERE id = ?")
        .get(creativeId) as any;
      if (!creative) {
        res.status(404).json({ error: { message: "Creative not found" } });
        return;
      }

      if (creative.status === "draft") {
        res.status(400).json({
          error: { message: "请先上传素材后再预览" },
        });
        return;
      }

      const theme = req.body?.theme || JSON.parse(creative.theme || "{}");
      const result = await startPreview(creativeId, theme, storageDir);

      res.json({ data: result });
    } catch (err: any) {
      res.status(500).json({ error: { message: err.message } });
    }
  });

  // POST /api/v1/creatives/:id/preview/stop
  router.post("/creatives/:id/preview/stop", (_req, res) => {
    stopPreview();
    res.json({ data: { stopped: true } });
  });

  return router;
}

/**
 * 当 Theme 保存时，若预览正在运行则更新配置
 */
export function onThemeSaved(
  creativeId: string,
  theme: Record<string, string>,
  storageDir: string
): void {
  updatePreviewConfig(creativeId, theme, storageDir);
}
