// @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 { 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 } });
    tagsList = await db.select().from(tags);
    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");
}

const vocabList = [
  {
    label: "Index",
    link: `/vocabulary`,
  },
].concat(
  tagsList.map((tag) => ({
    label: tag.name.charAt(0).toUpperCase() + tag.name.slice(1),
    link: `/vocabulary/${tag.name}`,
  })),
);

// 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: vocabList,
        },
        {
          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",
        },
      ],
      components: {
        Sidebar: "@/components/Sidebar.astro",
        PageSidebar: "@/components/PageSidebar.astro",
      },
    }),
    react(),
  ],

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