import type { UsersInfoResponse } from "@slack/web-api";

const { App } = (await import("@slack/bolt"));
import "dotenv/config";

const app = new App({
    token: process.env.SLACK_BOT_TOKEN,
    signingSecret: process.env.SLACK_SIGNING_SECRET,
});

const whitelist: string[] = (() => {
    try {
        return require('./whitelist.json')
    } catch (e) {
        return []
    }
})();

function checkUserOk(user: UsersInfoResponse['user']) {
    if (whitelist.includes(user!.id!)) return true

    return user!.is_admin || user!.is_owner || user!.is_primary_owner
}

const eligibilityCmd = async (ctx: any) => {
    await ctx.ack();

    const text = ctx.command.text.slice();
    let match;
    let userId = ctx.context.userId;
    let matchedBy = "no input"

    const iUser = await ctx.client.users.info({ user: ctx.context.userId! });

    if ((match = text.match(/\<\@(.+)\|(.+)>/))) {
        if (!checkUserOk(iUser.user!)) {
            matchedBy = "not allowed"
        } else {
            userId = match[1];
            matchedBy = "user mention"
        }
    } else if (text)
        matchedBy = "invalid input"


    const res = await fetch("https://verify.hackclub.dev/api/status", {
        method: "POST",
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
            "slack_id": userId
        }),
        redirect: "follow"
    }).then(res => res.json())

    if (res === `User ${userId} not found!`)
        return await ctx.respond({
            response_type: 'ephemeral',
            text: `${matchedBy !== "user mention" ? "You aren't" : `<@${userId}> isn't`} verified and therefore aren't eligible for rewards from your program.${matchedBy !== "user mention" ? `\nCheck out the <https://forms.hackclub.com/eligibility?slack_id=${userId}|eligiblity form> to verify.` : ""}${matchedBy == "not allowed" ? " (Only whitelisted users can check other people's verification statuses.)" : ""}`,
            unfurl_links: true
        })

    else if (res.status === "Insufficient") {
        return await ctx.respond({
            response_type: 'ephemeral',
            text: `${matchedBy !== "user mention" ? "You" : `<@${userId}>`} provided insufficient evidence that ${matchedBy !== "user mention" ? "you" : "they"} are a student.${matchedBy !== "user mention" ? `\nCheck out the <https://forms.hackclub.com/eligibility?slack_id=${userId}|eligiblity form> to re-verify.` : ""}${matchedBy == "not allowed" ? " (Only whitelisted users can check other people's verification statuses.)" : ""}`,
            unfurl_links: true
        })        
    }

    else if (res.status === "Unknown") {
        return await ctx.respond({
            response_type: 'ephemeral',
            text: `${matchedBy !== "user mention" ? "Your verification" : `<@${userId}>'s verification`} has not been accepted yet.${matchedBy == "not allowed" ? " (Only whitelisted users can check other people's verification statuses.)" : ""}`,
            unfurl_links: true
        })        
    }

    else if (res.status === "Ineligible") {
        if (matchedBy === "user mention") {
            return await ctx.respond({
                response_type: 'ephemeral',
                text: `<@${userId}>'s verification has been denied.`
            })
        } else {
            return await ctx.respond({
                response_type: 'ephemeral',
                text: `Your verification has been denied. If you believe this to be a mistake, please contact an admin of the program you are applying for.${matchedBy == "not allowed" ? " (Only whitelisted users can check other people's verification statuses.)" : ""},`
            })
        }
    }

    else if (res.status === "Sanctioned country") {
        if (matchedBy === "user mention") {
            return await ctx.respond({
                response_type: 'ephemeral',
                text: `<@${userId}> lives in a country that cannot have packages delivered to due to sanctions.`
            })
        } else {
            return await ctx.respond({
                response_type: 'ephemeral',
                text: `You live in a country that cannot have packages delivered to due to sanctions.${matchedBy == "not allowed" ? " (Only whitelisted users can check other people's verification statuses.)" : ""},`
            })
        }        
    }

    else {
        return await ctx.respond({
            response_type: 'ephemeral',
            text: `${matchedBy !== "user mention" ? "You have verified your" : `<@${userId}> has verified their`} student status, and ${matchedBy !== "user mention" ? "are" : "is"} ${res.status}.${matchedBy == "not allowed" ? " (Only whitelisted users can check other people's verification statuses.)" : ""}`,
            blocks: [
                {
                    type: 'section',
                    text: {
                        type: 'mrkdwn',
                        text: `${matchedBy !== "user mention" ? "You have verified your" : `<@${userId}> has verified their`} student status, and ${matchedBy !== "user mention" ? "are" : "is"} *${res.status}*.${matchedBy == "not allowed" ? " (Only whitelisted users can check other people's verification statuses.)" : ""}`
                    }
                }
            ]
        })
    }
}

app.command("/check-eligiblity", eligibilityCmd)
app.command("/check-eligibility", eligibilityCmd)

    ; (async () => {
        await app.start(60275);

        console.log('⚡️ Bolt app is running!');
    })();