import express from "express";
import cors from "cors";
import path from "path";
import { initDatabase } from "./db/database";
import { seedTemplates } from "./db/seed";
import { templatesRouter } from "./routes/templates";
import { creativesRouter } from "./routes/creatives";
import { assetsRouter } from "./routes/assets";
import { buildsRouter } from "./routes/builds";
import { previewRouter } from "./routes/preview";
import { onThemeSaved } from "./routes/preview";
import { errorHandler } from "./middleware/errorHandler";

const PORT = process.env.PORT || 3001;
const STORAGE_DIR = path.resolve(__dirname, "../../../storage");
const CLIENT_DIST = path.resolve(__dirname, "../../client/dist");

async function main() {
  // 初始化数据库
  const db = initDatabase(STORAGE_DIR);
  seedTemplates(db);

  const app = express();

  // 中间件
  app.use(cors());
  app.use(express.json());

  // API 路由
  app.use("/api/v1/templates", templatesRouter(db));
  app.use("/api/v1/creatives", creativesRouter(db, STORAGE_DIR, onThemeSaved));
  app.use("/api/v1", assetsRouter(db, STORAGE_DIR));
  app.use("/api/v1", buildsRouter(db, STORAGE_DIR, onThemeSaved));
  app.use("/api/v1", previewRouter(db, STORAGE_DIR));

  // 构建预览文件（真机扫码测试）
  const previewsDir = path.join(STORAGE_DIR, "previews");
  app.use("/q", express.static(previewsDir));
  app.use("/q", (_req, res) => res.status(404).send("Preview not found"));

  // 生产环境：serve React 静态文件
  app.use(express.static(CLIENT_DIST));
  app.get("*", (_req, res) => {
    res.sendFile(path.join(CLIENT_DIST, "index.html"));
  });

  // 错误处理
  app.use(errorHandler);

  app.listen(PORT, () => {
    console.log(`[platform] Server running at http://localhost:${PORT}`);
    console.log(`[platform] Storage: ${STORAGE_DIR}`);
  });
}

main().catch((err) => {
  console.error("Failed to start server:", err);
  process.exit(1);
});
