import express, { Request, Response } from 'express';
import { Controller, GET, Page, POST, BaseController } from '@BridgemanAccessible/ba-web-framework';
import { APICredentials, Subscriber, List } from '@BridgemanAccessible/listmonk-node-client';

@Controller()
class NewsletterRoutes extends BaseController {
    /** Listmonk credentials */
    private creds: APICredentials;

    constructor() {
        super();

        // Verify that the required environment variables are set
        if(typeof process.env.LISTMONK_HOST === 'undefined') { throw new Error('Missing environment variable: LISTMONK_HOST (hostname of Listmonk instance to use)'); }
        if(typeof process.env.LISTMONK_USERNAME === 'undefined') { throw new Error('Missing environment variable: LISTMONK_USERNAME (username to access Listmonk)'); }
        if(typeof process.env.LISTMONK_PASSWORD === 'undefined') { throw new Error('Missing environment variable: LISTMONK_PASSWORD (password to access Listmonk)'); }

        this.creds = {
            host: process.env.LISTMONK_HOST,
            username: process.env.LISTMONK_USERNAME,
            password: process.env.LISTMONK_PASSWORD
        }
    }
    
    @POST('/newsletter/signup', express.json())
    private async signUp(req: Request, res: Response) {
        const email = req.body.email;
        const name = req.body.name;

        const attribs: { [key: string]: any } = {};
        if(typeof req.body.phone !== 'undefined') {
            attribs.phone = req.body.phone;
        }
        
        try {
            // Get the newsletter list
            const list = await List.find((list: List) => list.getName() === 'Bridgeman Accessible Newsletter', this.creds);
            if(typeof list === 'undefined') {
                throw new Error('Newsletter list not found');
            }

            // Create the subscriber
            await (await Subscriber.create(email, name, 'enabled', [list], attribs, false, this.creds)).save();
        }
        catch(e) {
            console.error(e);
            res.status(500).send('Issue with signing user up');
            return;
        }

        res.status(200).json({ message: 'Sign up successful' });
    }

    @Page('Newsletter', 'newsletter.ejs', ['newsletter-signup'])
    @GET('/newsletter')
    private signupPage(req: Request, res: Response) {}
}