import "@std/dotenv/load";
import { Hono } from "hono";
import { getGroceryList, getRecipesList, storeRecipe } from "./services.ts";
import db from "./db.ts";
import { Layout } from "./web/tsx/layout.tsx";
import { AddRecipe, GroceryList, RecipesList } from "./web/tsx/components.tsx";
import { serveStatic } from "hono/deno";
import { basicAuth } from "hono/basic-auth";

const httpUser = Deno.env.get("HTTP_USER");
const httpPass = Deno.env.get("HTTP_PASS");

const app = new Hono();

app.use("/style.css", serveStatic({ path: "./web/static/style.css" }));

if (httpUser && httpPass)
  app.use(
    "/*",
    basicAuth({
      username: httpUser,
      password: httpPass,
    })
  );

app.get("/", (c) => {
  const recipes = getRecipesList(db);
  return c.html(
    <Layout url={c.req.url}>
      <AddRecipe />
      <RecipesList recipes={recipes} />
    </Layout>
  );
});

app.get("/grocery", (c) => {
  const url = new URL(c.req.url);
  const recipeIds =
    url.searchParams.get("recipeIds")?.split(",").map(Number) || [];
  const recipes = getRecipesList(db, recipeIds);
  console.log({ recipes });
  const ingredients = getGroceryList(db, recipeIds);
  return c.html(
    <Layout url={c.req.url}>
      <GroceryList recipes={recipes} ingredients={ingredients} />
    </Layout>
  );
});

app.post("/add-recipe", async (c) => {
  const body = await c.req.formData();
  const recipeId = body.get("recipeId");
  if (!recipeId) return c.redirect("/");
  try {
    const result = await storeRecipe(db, recipeId as string);
    console.log(result);
    return c.redirect("/?msg=Recipe added successfully");
  } catch (error) {
    console.error(error);
    return c.redirect("/?error=An error occured");
  }
});

app.post("/add-grocery-list", async (c) => {
  const body = await c.req.formData();
  const enabledRecipeIds = [...body.entries()]
    .filter(([_, value]) => value === "on")
    .map(([key]) => key);
  return c.redirect(`/grocery?recipeIds=${enabledRecipeIds.join(",")}`);
});

export default app;
