import { EJSON } from "@/src/exports/client-exports";
import { PagePropsType, URLQueryType, User } from "@/src/types";
import grabDirNames from "@/src/utils/grab-dir-names";
import grabTurboCiConfig from "@/src/utils/grab-turboci-config";
import parsePageUrl from "@/src/utils/parse-page-url";
import userAuth from "@/src/utils/user-auth";
import { readFileSync } from "fs";
import _ from "lodash";
import { GetServerSidePropsContext, GetServerSidePropsResult } from "next";

type PropsFnParams = {
    user: User;
    props?: PagePropsType;
    query?: URLQueryType;
};

type Params = {
    ctx: GetServerSidePropsContext;
    props?: PagePropsType;
    propsFn?: (
        params: PropsFnParams,
    ) => Promise<Omit<PagePropsType, "user"> | false | string>;
};

const { TURBOCI_DEPLOYMENT_ID_FILE } = grabDirNames();

export default async function defaultAdminProps({
    ctx,
    props,
    propsFn,
}: Params): Promise<GetServerSidePropsResult<PagePropsType>> {
    const { req, res } = ctx;
    const query: URLQueryType = ctx.query;
    const { singleRes: user } = await userAuth({ req });

    const deployment = grabTurboCiConfig();
    const deployment_id = readFileSync(TURBOCI_DEPLOYMENT_ID_FILE, "utf-8");

    const service = query.service_name
        ? deployment.services.find(
              (srv) => srv.service_name == query.service_name,
          ) || null
        : null;

    const children_services = service?.service_name
        ? deployment.services.filter(
              (srv) => srv.parent_service_name == service.service_name,
          ) || null
        : null;

    if (query.service_name && !service?.service_name) {
        return {
            redirect: {
                destination: `/admin/services`,
                statusCode: 307,
            },
        };
    }

    if (!user?.id) {
        return {
            redirect: {
                destination: "/auth/login",
                permanent: false,
            },
        };
    }

    const propsFnProps = propsFn
        ? await propsFn?.({ user, query, props })
        : undefined;

    if (typeof propsFnProps == "boolean" && !propsFnProps) {
        return {
            redirect: {
                destination: "/admin",
                permanent: false,
            },
        };
    }

    if (typeof propsFnProps == "string") {
        return {
            redirect: {
                destination: propsFnProps,
                permanent: false,
            },
        };
    }

    const finalAdminUrl = parsePageUrl(req.url, true);

    const defaultPageProps: PagePropsType = {
        query,
        user,
        pageUrl: finalAdminUrl,
        deployment,
        deployment_id,
        service,
        children_services,
    };

    let finalProps = _.merge(props, propsFnProps, defaultPageProps);

    return {
        props: { ...finalProps },
    };
}
