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

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

export const handler: Handlers<TeamPageProps> = {
  async GET(request, context) {
    // 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 {
      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>
    </>
  );
}
