import { ResponsiblePartyConsent } from "entity";
import { NextFunction, Response } from "express";
import { Request } from "express-jwt";
import Joi from "joi";
import { ILogObj, Logger } from "tslog";
import { ReturnHelper } from "../helpers/express/return";
import { Language } from "../langs/lang";
import { OrmHelper } from "../helpers/orm";
import moment from "moment";

const log: Logger<ILogObj> = new Logger({
    name: "[ResponsiblePartyConsentController]",
    type: "pretty",
});

export class ResponsiblePartyConsentController {
    static async body(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['Responsible Party Consent']
            #swagger.security = [{ "bearerAuth": [] }]
            #swagger.parameters['type'] = { in: 'query', required: false, type: 'string' }
        */
        try {
            const schema = Joi.object({
                type: Joi.string().optional().allow("").label("Type"),
            });

            const { type } = await schema.validateAsync(req.query);

            let query = OrmHelper.DB.getRepository(ResponsiblePartyConsent)
                .createQueryBuilder("ResponsiblePartyConsent");

            if (type && type !== "") {
                query = query.where("ResponsiblePartyConsent.type = :type", { type });
            }

            const data = await query.getMany();

            return ReturnHelper.successResponselist(
                res,
                200,
                Language.lang.success_view,
                data.length,
                1,
                data.length,
                data
            );
        } catch (e: unknown) {
            log.error(e);
            const err = e as Error;
            return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_view, err.message);
        }
    }

    static async create(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
         #swagger.tags = ['Responsible Party Consent']
         #swagger.security = [{ "bearerAuth": [] }]
         #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/responsiblepartyconsent" } } } }
         */
        const queryRunner = OrmHelper.DB.createQueryRunner();
        await queryRunner.startTransaction();
        try {
            const typeEnum = [
                "responsible-party-consent",
                "patient-education",
                "inpatient-admission-consent",
                "provision-of-information",
                "ward-class-upgrade-entitlement",
            ];

            // create
            const schema = Joi.object().keys({
                bodytext: Joi.string().required().label("Body Text"),
                type: Joi.string().valid(...typeEnum).required().label("Type"),
            });

            let param: any = await schema.validateAsync(req.body);

            let responsiblepartyconsent = new ResponsiblePartyConsent();
            responsiblepartyconsent.body = param.bodytext;
            responsiblepartyconsent.type = param.type;
            responsiblepartyconsent.created_by = req.auth?.data.name;
            responsiblepartyconsent.updated_by = req.auth?.data.name;
            await queryRunner.manager.save(responsiblepartyconsent);

            await queryRunner.commitTransaction();
            return ReturnHelper.successResponseAny(res, 200, Language.lang.success_insert, responsiblepartyconsent);
        } catch (e: unknown) {
            await queryRunner.rollbackTransaction();
            log.error(e);
            const err = e as Error;
            return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_view, err.message);
        } finally {
            await queryRunner.release();
        }
    }

    static async update(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
         #swagger.tags = ['Responsible Party Consent']
         #swagger.security = [{ "bearerAuth": [] }]
         #swagger.parameters['id'] = { in: 'path', type: 'string' }
         #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/responsiblepartyconsent" } } } }
         */
        const queryRunner = OrmHelper.DB.createQueryRunner();
        await queryRunner.startTransaction();
        try {
            req.body.id = req.params["id"];
            const typeEnum = [
                "responsible-party-consent",
                "patient-education",
                "inpatient-admission-consent",
                "provision-of-information",
                "ward-class-upgrade-entitlement",
            ];
            const schema = Joi.object().keys({
                id: Joi.string().uuid().required().label("Room ID"),
                bodytext: Joi.string().required().label("Body Text"),
                type: Joi.string().valid(...typeEnum).required().label("Type"),
            });
            let param: any = await schema.validateAsync(req.body);

            let responsiblepartyconsent = await OrmHelper.DB.getRepository(ResponsiblePartyConsent)
                .createQueryBuilder("ResponsiblePartyConsent")
                .where("ResponsiblePartyConsent.id = :id", { id: param.id })
                .getOne();
            if (!responsiblepartyconsent) throw { message: "Responsible Party Consent " + Language.lang.failed_not_found };

            responsiblepartyconsent.body = param.bodytext;
            responsiblepartyconsent.type = param.type;
            responsiblepartyconsent.updated_by = req.auth?.data.name;
            responsiblepartyconsent.updated_at = moment().toDate();
            await queryRunner.manager.save(responsiblepartyconsent);

            await queryRunner.commitTransaction();
            return ReturnHelper.successResponseAny(res, 200, Language.lang.success_update, responsiblepartyconsent);
        } catch (e: unknown) {
            await queryRunner.rollbackTransaction();
            log.error(e);
            const err = e as Error;
            return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_view, err.message);
        } finally {
            await queryRunner.release();
        }
    }
}
