import { Handlers, PageProps } from "$fresh/server.ts";
import { getTeam, getTeamUsers, isUserInTeam } from "@/db/mod.ts";
import { type Team, type User } from "@/types.ts";
import { type ContextState } from "@/types.ts";

interface TeamPageProps {
  team: Team;
  users: User[];
}

export const handler: Handlers<TeamPageProps, ContextState> = {
  async GET(request, context) {
    if (!context.state.user?.id) {
      // unauthenticated requests may not view teams
      return await context.renderNotFound();
    }
    // TODO: implement this with row-level security?
    // TODO: do I just use supabase at this point?
    // TODO: only allow logged-in users to view teams (and most resources!)
    // TODO: only allow users that are a member of a team to view them
    // NOTE: maybe teams can be public...?
    const { id } = context.params;

    console.debug({ request, context });
    try {
      if (!await isUserInTeam(context.state.user?.id, id)) {
        // users that are not a member of a team may not view it
        return await context.renderNotFound();
      }
      const team = await getTeam({ id });
      const users = await getTeamUsers(team) || [];
      return await context.render({ team, users });
    } catch (e) {
      console.error(`Error handling team page for ID '${id}'`, e);
      return await context.renderNotFound();
    }
  },
};

export default function Team(
  { data: { team: { createdAt, displayName }, users } }: PageProps<
    TeamPageProps
  >,
) {
  return (
    <>
      <a href="/dashboard">Back to dashboard</a>
      <h1>{displayName} - created {createdAt.toLocaleString()}</h1>
      <h1 class="mt-4">Team Members</h1>
      <ul>
        {users.map((user) => (
          <li key={user.id}>
            <a href={`/user/${user.id}`}>
              {(user.displayName || user.username).trim()}
            </a>
          </li>
        ))}
      </ul>
    </>
  );
}
