// @ts-check
import { defineConfig } from "astro/config";
import starlight from "@astrojs/starlight";
import react from "@astrojs/react";
import node from "@astrojs/node";
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import { eq } from "drizzle-orm";
import { tags } from "./src/lib/db/schema.ts";
import "dotenv/config";

// Load tags from database for sidebar
// Explicitly type tagsList as an array of objects with a 'name' property
/** @type {{ name: string }[]} */
let tagsList = [];
try {
  const connectionString = process.env.DATABASE_URL || "";
  if (connectionString) {
    const client = postgres(connectionString);
    const db = drizzle(client, { schema: { tags } });
    // Only get page-level tags for the sidebar
    tagsList = await db.select().from(tags).where(eq(tags.level, 'page'));
    await client.end();
  } else {
    console.warn(
      "⚠️  DATABASE_URL not found - sidebar will not include vocabulary tags",
    );
  }
} catch (error) {
  const errorMessage =
    typeof error === "object" && error !== null && "message" in error
      ? error.message
      : String(error);
  console.warn("⚠️  Could not load tags from database:", errorMessage);
  console.warn("   Sidebar will not include vocabulary tags");
}

// https://astro.build/config
export default defineConfig({
  vite: {
    resolve: {
      alias: {
        "@": "/src",
      },
    },
  },

  integrations: [
    starlight({
      title: "हिंदकी",
      customCss: [
        // Path to your custom CSS file
        "./src/styles/custom.css",
      ],
      sidebar: [
        {
          label: "Home",
          link: "/",
        },
        {
          label: "About Me",
          link: "/about-me",
        },
        {
          label: "Grammar",
          autogenerate: { directory: "grammar" },
        },
        {
          label: "Vocabulary",
          items: [], // Replace at runtime using API
        },
        {
          label: "Culture",
          autogenerate: { directory: "culture" },
        },
        {
          label: "How I Built This",
          autogenerate: { directory: "how-i-built-this" },
          collapsed: true,
        },
        {
          label: "Add Vocabulary",
          link: "/edit/add-vocab",
        },
        {
          label: "Learn",
          link: "/learn",
        },
        {
          label: "Journal",
          items: [], // Replace at runtime using getCollection
        },
      ],
      components: {
        Sidebar: "@/components/Sidebar.astro",
        PageSidebar: "@/components/PageSidebar.astro",
      },
    }),
    react(),
  ],

  adapter: node({
    mode: "standalone",
  }),
});
