import { Handlers } from "$fresh/server.ts";
import { deleteCookie, getCookies } from "$std/http/cookie.ts";
import { deleteToken } from "@/db/mod.ts";

export const handler: Handlers<unknown> = {
  async GET(request: Request, context) {
    const { lsauth } = getCookies(request.headers);
    if (lsauth) {
      console.log("deleteToken:", await deleteToken(lsauth));
    }

    const newUrl = new URL(request.url);
    newUrl.pathname = "/login";
    const response = await context.render();

    const headers = new Headers(response.headers);
    deleteCookie(headers, "lsauth");
    headers.set("location", newUrl.toString());

    const actualResponse = new Response(response.body, {
      ...response,
      headers: headers,
      status: 302,
    });

    return actualResponse;
  },
};

export default function LoggedOut() {
  return (
    <p>
      If you were logged in before, we've logged you out.
    </p>
  );
}
