import {
  ActionFunctionArgs,
  LoaderFunctionArgs,
  redirect,
  useLoaderData,
} from "react-router";
import { createFilePageURL } from "#lib/urls";
import { apiFetchArchiveFile, apiSetArchiveFilePassword } from "#api/files";
import { PageSkeleton } from "#components/pages";
import { ArchiveFileOverview, IArchiveFile } from "#entities/files";

import * as styles from "./archive.module.scss";

interface IProps {
  archive: IArchiveFile;
}

export function ArchiveFilePage() {
  const { archive } = useLoaderData() as IProps;
  const title = `Archive file "${archive.file.hash}" details`;
  const heading = "Archive File Details";

  return (
    <PageSkeleton name="archives" title={title} heading={heading}>
      <ArchiveFileOverview className={styles.article} archiveFile={archive} />
    </PageSkeleton>
  );
}

export async function loader({ params }: LoaderFunctionArgs): Promise<IProps> {
  const fileHash = params.file_hash?.trim();

  if (!fileHash) {
    throw new Error("File hash is required.");
  }

  const archive = await apiFetchArchiveFile(fileHash);

  if (!archive) {
    throw new Error("Archive file not found.");
  }

  return {
    archive,
  };
}

export async function action({ params, request }: ActionFunctionArgs) {
  try {
    const method = request.method;

    switch (method) {
      case "PATCH": {
        const fileHash = params.file_hash?.trim();

        if (!fileHash) {
          throw new Error("File hash is required.");
        }

        const data = await request.formData();
        const password = data.get("password") as string | null;

        if (!password) {
          throw new Error("Password is required.");
        }

        await apiSetArchiveFilePassword(fileHash, password);
        const url = String(createFilePageURL(fileHash));

        return redirect(url);
      }

      default: {
        throw new Error(`Unknown method "${method}".`);
      }
    }
  } catch (error) {
    return error;
  }
}
