import { MiddlewareHandlerContext } from "$fresh/server.ts";
import { deleteCookie, getCookies } from "$std/http/cookie.ts";
import { getUserFromNonExpiredLoginToken } from "@/db/mod.ts";
import { type ContextState, type PublicUser, type User } from "@/types.ts";
import { log } from "@/log.ts";

function toPublicUser(user: User): PublicUser {
  const {
    createdAt: _createdAt,
    updatedAt: _updatedAt,
    passwordDigest: _passwordDigest,
    ...publicUser
  } = user;
  return publicUser;
}

async function currentUser(
  request: Request,
  context: MiddlewareHandlerContext<ContextState>,
) {
  let hasBadAuthCookie = false;
  const { lsauth } = getCookies(request.headers);
  log.debug("lsauth cookie:", lsauth);
  if (lsauth) {
    try {
      context.state.user = toPublicUser(
        await getUserFromNonExpiredLoginToken(lsauth),
      );
    } catch (e) {
      hasBadAuthCookie = true;
    }
  }
  const resp = await context.next();
  if (resp) {
    if (hasBadAuthCookie) deleteCookie(resp.headers, "lsauth");
  }
  return resp;
}

export async function serverHeader(
  _request: Request,
  context: MiddlewareHandlerContext<ContextState>,
) {
  const resp = await context.next();
  if (resp) {
    resp.headers.set("server", "fresh server");
  }
  return resp;
}

export async function someState(
  _request: Request,
  context: MiddlewareHandlerContext<ContextState>,
) {
  context.state.something = "I said something!";
  return await context.next();
}

export const handler = [
  someState,
  currentUser,
  serverHeader,
];
