import { Request as ExpressRequest, Response as ExpressResponse } from "express";
import { existsSync, promises } from "fs";
import { join } from "path";
import { Option } from "@shared/common/async_utils";
import { rpcClient } from "src/utils/rpc";
import { ENV } from "src/utils/environment";

export interface MDText {
    text: string;
}

const FILE_PATH = join(ENV.WEB_DATA_PATH, "rules.md");

type GetResult = Promise<ExpressResponse<Option<MDText, { error: string }>>>;
export const get = async (req: ExpressRequest, res: ExpressResponse): GetResult => {
    if (!existsSync(FILE_PATH)) {
        return res.json({
            ok: true,
            text: "",
        });
    }
    const fileData = await promises.readFile(FILE_PATH);
    return res.json({
        ok: true,
        text: fileData.toString("utf-8"),
    });
};

type PostResult = Promise<ExpressResponse<Option<unknown, { error: string }>>>;
export const post = async (req: ExpressRequest, res: ExpressResponse): PostResult => {
    const isText = (body: unknown):
        body is MDText => body instanceof Object
                            && (body as Record<string, unknown>).text !== undefined;

    if (!isText(req.body)) {
        return res.json({
            ok: false,
            error: "No text",
        });
    }

    if (!req.session?.userId) {
        return res.json({
            ok: false,
            error: "Not logged in, please log in",
        });
    }

    const { authorised } = await rpcClient.userAuthorised({ userId: req.session.userId });
    if (!authorised) {
        return res.json({
            ok: false,
            error: "Not authorised, please log in",
        });
    }

    await promises.writeFile(FILE_PATH, req.body.text);

    return res.json({ ok: true });
};
