import Fastify from "fastify";
import cors from "@fastify/cors";
import cookie from "@fastify/cookie";
import staticFiles from "@fastify/static";
import path from "path";
import { fileURLToPath } from "url";
import { TinaNodeBackend, createDatabase } from "@tinacms/datalayer";
import { GitHubProvider } from "tinacms-gitprovider-github";
import { createOIDCBackendAuth } from "./auth/oidc-backend.js";
import { PostgresLevel } from "./database/postgres-adapter.js";
import { config } from "./config.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const fastify = Fastify({
  logger: true,
});

// Plugins
await fastify.register(cors, {
  origin: true,
  credentials: true,
});

await fastify.register(cookie);

// Static files (Tina Admin build)
await fastify.register(staticFiles, {
  root: path.join(__dirname, "../admin"),
  prefix: "/admin/",
});

// Database Adapter
const dbAdapter = new PostgresLevel({
  connectionString: config.DATABASE_URL,
  namespace: config.GITHUB_BRANCH,
});

// Git Provider
const gitProvider = new GitHubProvider({
  repo: config.GITHUB_REPO,
  owner: config.GITHUB_OWNER,
  token: config.GITHUB_TOKEN,
  branch: config.GITHUB_BRANCH,
});

// Create Database
const database = createDatabase({
  gitProvider,
  databaseAdapter: dbAdapter,
});

// Tina Backend Handler
const tinaBackend = TinaNodeBackend({
  authProvider: createOIDCBackendAuth(),
  databaseClient: database,
});

// Routes
fastify.all("/api/tina/*", async (request, reply) => {
  await tinaBackend(request.raw, reply.raw);
});

// Route racine pour /admin
fastify.get("/admin", async (request, reply) => {
  return reply.sendFile("index.html");
});

// Health check
fastify.get("/health", async () => {
  return { status: "ok" };
});

// Start server
fastify.listen({
  port: parseInt(config.PORT),
  host: "0.0.0.0",
});
