import { Response, NextFunction, Application } from "express";
import { Request } from "express-jwt";
import { ReturnHelper } from "../../helpers/express/return";
import { OrmHelper } from "../../helpers/orm";
import Joi from "joi";
import { ILogObj, Logger } from "tslog";
import { Language } from "../../langs/lang";
import { InitialStock, ItemMaster, Room, ItemOrigin, RoomStock, Paging } from "entity";
import CommonHelper from "../../helpers/common";
import * as fastcsv from 'fast-csv';
import dayjs from "dayjs";
import { InitialStockModel } from "../../model/initial_stock";

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

export class InitialStockController {
    static async list(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['Pharmacy - InitialStock']
            #swagger.security = [{ "bearerAuth": [] }]
            #swagger.parameters['filter'] = { description: '', in: 'query', type: 'string' }
            #swagger.parameters['limit'] = { in: 'query', required: true, type: 'number' }
            #swagger.parameters['page'] = { in: 'query', required: true, type: 'number' }
            #swagger.parameters['with_deleted'] = { in: 'query', required: true, type: 'boolean' }
            #swagger.parameters['order_field'] = { in: 'query', required: true, type: 'string' }
            #swagger.parameters['order_direction'] = { in: 'query', required: true, schema: { '@enum': ['ASC', 'DESC'] } }
        */
        try {
            const schema = Joi.object().keys({
                filter: Joi.string().allow("").optional().label("Filter"),
                page: Joi.number().required().min(1).label("Page"),
                limit: Joi.number().required().min(1).label("Limit"),
                with_deleted: Joi.bool().required().label("With Deleted"),
                order_field: Joi.string().required().label("Order Field"),
                order_direction: Joi.string().allow("asc", "desc").required().label("Order Direction"),
            });

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

            let filter = param.filter && param.filter !== "" ? JSON.parse(param.filter) : {};

            var query = await InitialStockModel.list(filter);

            const offset = (param.page - 1) * param.limit;
            let limit = param.limit;

            const res_count = query;
            const res_list = query.select([
                'InitialStock.id',
                'InitialStock.exp_date',
                'InitialStock.stock',
                'InitialStock.batch',
                'ItemMaster.item_name',
                'Room.room',
                'ItemOrigin.origin_name',
            ])
                .leftJoin("InitialStock.itemmaster", "ItemMaster")
                .leftJoin("InitialStock.room", "Room")
                .leftJoin("InitialStock.itemorigin", "ItemOrigin")
                .orderBy("InitialStock." + param.order_field, param.order_direction)
                .offset(offset)
                .limit(limit);

            if (param.with_deleted) {
                res_count.withDeleted();
                res_list.withDeleted();
            }

            const current_page = param.page;
            const total_count_data = await res_count.getCount();
            const list_data = await res_list.getMany();
            const count_data = CommonHelper.countObject(list_data);

            return ReturnHelper.successResponselist(res, 200, Language.lang.success_view, count_data, current_page, total_count_data, list_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<Response> {
        /*
        #swagger.tags = ['Pharmacy - InitialStock']
        #swagger.security = [{
            "bearerAuth": []
        }]
        
        #swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                         $ref: "#/components/schemas/initial_stock"
                    }  
                }
            }
        }
        */
        const queryRunner = OrmHelper.DB.createQueryRunner();
        await queryRunner.startTransaction();
        try {
            const schema = Joi.object().keys({
                itemmaster: Joi.string().uuid().required().label("Item Master ID"),
                room: Joi.string().uuid().required().label("Room ID"),
                itemorigin: Joi.string().uuid().required().label("Item Origin ID"),
                batch: Joi.string().label("Batch"),
                exp_date: Joi.date().required().label("Exp Date"),
                stock: Joi.number().required().label("Stock"),
            });

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

            const itemmaster = OrmHelper.DB.getRepository(ItemMaster).findOneBy({ id: param.itemmaster });
            const room = OrmHelper.DB.getRepository(Room).findOneBy({ id: param.room })
            const itemorigin = OrmHelper.DB.getRepository(ItemOrigin).findOneBy({ id: param.itemorigin });

            if (!itemmaster) throw { message: "Item Master not found" };
            if (!room) throw { message: "Room not found" };
            if (!itemorigin) throw { message: "Item Origin not found" };

            const initial_stock = new InitialStock();
            initial_stock.itemmaster = param.itemmaster;
            initial_stock.room = param.room;
            initial_stock.itemorigin = param.itemorigin;
            initial_stock.batch = param.batch;
            initial_stock.exp_date = param.exp_date;
            initial_stock.stock = param.stock;
            await queryRunner.manager.save(initial_stock);

            const room_stock = new RoomStock();
            room_stock.itemmaster = param.itemmaster;
            room_stock.room = param.room;
            room_stock.batch = param.batch; 
            room_stock.exp_date = new Date(param.exp_date);
            room_stock.total_stock = param.stock;
            room_stock.itemorigin = param.itemorigin;
            await queryRunner.manager.save(room_stock);

            await queryRunner.commitTransaction();

            return ReturnHelper.successResponseAny(res, 200, Language.lang.success_insert, initial_stock);

        } catch (e: unknown) {
            log.error(e);
            const err = e as Error;

            return ReturnHelper.errorResponse(res, 500, 401, Language.lang.failed_insert, err.message);
        }
    }
}