import { FreshContext, Handlers, PageProps } from "$fresh/server.ts";
import AuthorCard from "../../components/AuthorCard.tsx";
import { Post } from "../../types/index.ts";
import { PostCarousel } from "../../components/PostCarousel.tsx";

export const handler: Handlers<PageData> = {
  async GET(_req: Request, ctx: FreshContext) {
    try {
      const [authorResponse, authorPostResponse] = await Promise.all([
        fetch(`${Deno.env.get("BASE_URI_API")}/authors/${ctx.params.id}`),
        fetch(`${Deno.env.get("BASE_URI_API")}/authors/${ctx.params.id}/posts`),
      ]);

      const [authorData, authorPostData] = await Promise.all([
        authorResponse.json(),
        authorPostResponse.json(),
      ]);

      return ctx.render({
        authorData,
        authorPostData,
      });
    } catch (error) {
      return ctx.render({
        error: error.message,
        authorData: null,
        authorPostData: [],
      });
    }
  },
};

export default function AuthorIdentifier({ data }: PageProps<PageData>) {
  const { authorData, authorPostData, error } = data;

  if (error) {
    return (
      <div>
        <h1>Error Loading Author Information</h1>
        <p>{error}</p>
      </div>
    );
  }

  if (!authorData) {
    return <div>No author found</div>;
  }

  return (
    <>
      <div>
        <AuthorCard author={authorData} isIdentified={true} />
      </div>
      <div>
        <PostCarousel posts={authorPostData} />
      </div>
    </>
  );
}

interface PageData {
  error?: string;
  authorData: AuthorResponse;
  authorPostData: Array<Post>;
}

export type AuthorResponse = {
  author_id: number;
  first_name: string;
  last_name: string;
  bio: string;
  image?: string;
};
