import Fastify from "fastify";
import cors from "@fastify/cors";
import jwt from "@fastify/jwt";
import multipart from "@fastify/multipart";
import fastifyStatic from "@fastify/static";
import { config } from "./config.js";
import { migrate } from "./db.js";
import { authRoutes } from "./auth.js";
import { folderRoutes } from "./folders.js";
import { modelRoutes } from "./models.js";
import { storageStatus } from "./storage.js";

migrate();

const app = Fastify({
  logger: true,
  bodyLimit: 1024 * 1024 * 20
});

await app.register(cors, {
  origin: true,
  credentials: true
});
await app.register(jwt, {
  secret: config.jwtSecret
});
await app.register(multipart, {
  limits: {
    fileSize: 1024 * 1024 * 200
  }
});
await app.register(fastifyStatic, {
  root: config.storageDir,
  prefix: "/storage/"
});

app.get("/api/health", async () => ({ ok: true, storage: storageStatus() }));

await app.register(authRoutes);
await app.register(folderRoutes);
await app.register(modelRoutes);

app.setErrorHandler((error, _request, reply) => {
  const fastifyError = error as { statusCode?: number; message?: string };
  const statusCode = fastifyError.statusCode && fastifyError.statusCode >= 400 ? fastifyError.statusCode : 500;
  app.log.error(error);
  reply.code(statusCode).send({
    message: statusCode === 500 ? "服务器内部错误" : fastifyError.message
  });
});

await app.listen({ host: config.host, port: config.port });
