import { notFound } from "next/navigation";

import { CustomerPageShell } from "@/app/customer/_components/customer-page-shell";
import { DiscussionThreadForm } from "@/app/customer/[tenant]/discussion-board/_components/discussion-thread-form";
import { DISCUSSION_BOARD_PERMISSION } from "@/app/customer/[tenant]/discussion-board/_lib/discussion-board-route";
import {
  fetchDiscussionBoardView,
  fetchFormOptions,
} from "@/app/customer/[tenant]/discussion-board/_lib/discussion-board-server-api";
import { ErrorBanner } from "@/components/shared/error-banner";
import { getCustomerSessionContext } from "@/lib/frontend-auth/server";

type PageProps = {
  params: Promise<{ tenant: string; id: string }>;
};

export default async function CustomerDiscussionBoardUpdatePage({ params }: PageProps) {
  const { tenant, id } = await params;
  const threadToken = decodeURIComponent(id).trim();
  if (!threadToken) {
    notFound();
  }

  const session = await getCustomerSessionContext(tenant);
  const hasPermission = session.permissions.routes.includes(DISCUSSION_BOARD_PERMISSION);

  if (!hasPermission) {
    return (
      <CustomerPageShell>
        <ErrorBanner message="You do not have permission to edit discussion topics." />
      </CustomerPageShell>
    );
  }

  const [viewResult, formOptionsResult] = await Promise.all([
    fetchDiscussionBoardView(tenant, threadToken),
    fetchFormOptions(tenant),
  ]);

  if (viewResult.errorMessage || !viewResult.data) {
    return (
      <CustomerPageShell>
        <ErrorBanner message={viewResult.errorMessage ?? "Thread not found."} />
      </CustomerPageShell>
    );
  }

  if (!viewResult.data.isThreadAuthor) {
    return (
      <CustomerPageShell>
        <ErrorBanner message="You can only edit topics you created." />
      </CustomerPageShell>
    );
  }

  const initialTagIds = viewResult.data.tags.map((tag) => tag.tag_id);

  return (
    <CustomerPageShell>
      {formOptionsResult.errorMessage ? (
        <ErrorBanner message={formOptionsResult.errorMessage} />
      ) : null}
      <DiscussionThreadForm
        tenant={tenant}
        mode="update"
        formOptions={formOptionsResult.data ?? { tags: [], visibilityChoices: [] }}
        initialThread={viewResult.data.thread}
        initialTagIds={initialTagIds}
      />
    </CustomerPageShell>
  );
}
