import express, {Express, Request, Response} from 'express';
import {ShortenedLink} from "../models/ShortenedLink";

const app: Express = express();

app.get("*", async (req: Request, res: Response) => {
    const link = req.originalUrl.substring(1) || "home";
    let redirect_url = "https://sheepstar.xyz";

    // Search provided link
    const found = await ShortenedLink.findOne({shortenedId: link});
    if (found != null) {
        // Update redirect url
        redirect_url = found.originalUrl;

        // Increment clicks
        await found.updateOne({$inc: {clicks: 1}}).exec();
    }

    // Redirect to url
    res.status(301).header("Location", redirect_url).end();
});

/** Logs something with a shortener prefix */
const log = (msg: string) => console.log(`[Shortener] ${msg}`);

/** Starts the shortener service */
export const startServer = (port: number = 8672) => app.listen(port, () => log(`Listening on port ${port}`));