import { DoctorItemPackage, ItemMaster, ItemPrice, SellingPricePercentage, User, PharmacyInfo, RoomToPharmacy } 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 { DoctorItemPackageModel } from "../model/doctor_item_package";
import { OrmHelper } from "../helpers/orm";
import CommonHelper from "../helpers/common";

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

export class DoctorItemPackageController {
    static async list(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['Doctor Item Package']
            #swagger.security = [{ "bearerAuth": [] }]
            #swagger.parameters['doctor_id'] = { in: 'query', required: true, type: 'string' }
            #swagger.parameters['room_id'] = { in: 'query', required: true, type: 'string' }
            #swagger.parameters['filter'] = { description: '', in: 'query', type: 'string' }
            #swagger.parameters['page'] = { in: 'query', required: true, type: 'number' }
            #swagger.parameters['limit'] = { in: 'query', required: true, type: 'number' }
            #swagger.parameters['order_field'] = { in: 'query', required: false, type: 'string' }
            #swagger.parameters['order_direction'] = { in: 'query', required: false, schema: { '@enum': ['ASC', 'DESC'] } }
        */
        try {
            const schema = Joi.object().keys({
                doctor_id: Joi.string().uuid().required().label("Doctor ID"),
                room_id: Joi.string().uuid().required().label("Room ID"),
                filter: Joi.string().allow("").optional().label("Filter"),
                page: Joi.number().required().min(1).label("Page"),
                limit: Joi.number().required().min(1).label("Limit"),
                order_field: Joi.string().optional().label("Order Field"),
                order_direction: Joi.string().allow("asc", "desc").optional().label("Order Direction"),
            });

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

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

            let filterObj = { ...filter } as any;
            delete filterObj.any;
            filterObj = { ...filterObj, "DoctorItemPackage.doctor": param.doctor_id };

            const query = await DoctorItemPackageModel.list(filterObj, filterAny);

            const orderField = param.order_field || "id";
            const orderDirection = param.order_direction || "asc";

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

            const pharmacyInfoRow = await OrmHelper.DB
                .getRepository(PharmacyInfo)
                .createQueryBuilder("pharmacy_info")
                .select("pharmacy_info.default_room_id", "default_room_id")
                .where("pharmacy_info.deleted_at IS NULL")
                .orderBy("pharmacy_info.created_at", "DESC")
                .limit(1)
                .getRawOne<{ default_room_id: string | null }>();

            const defaultRoomId = pharmacyInfoRow?.default_room_id ?? null;

            const roomToPharmacyRow = await OrmHelper.DB
                .getRepository(RoomToPharmacy)
                .createQueryBuilder("room_to_pharmacy")
                .select("room_to_pharmacy.pharmacy_room_id", "pharmacy_room_id")
                .where("room_to_pharmacy.deleted_at IS NULL")
                .andWhere("room_to_pharmacy.room_id = :roomId", { roomId: param.room_id })
                .orderBy("room_to_pharmacy.created_at", "DESC")
                .limit(1)
                .getRawOne<{ pharmacy_room_id: string | null }>();

            const pharmacyRoomId = roomToPharmacyRow?.pharmacy_room_id ?? null;

            const current_page = param.page;
            const total_count_data = await query.getCount();

            // Query 1: packages only (pagination is correct)
            const packages = await query
                .select([
                    "DoctorItemPackage.id",
                    "DoctorItemPackage.name",
                    "DoctorItemPackage.description",
                    "DoctorItemPackage.active",
                ])
                .orderBy("DoctorItemPackage." + orderField, orderDirection)
                .offset(offset)
                .limit(param.limit)
                .getMany();

            if (!packages || packages.length === 0) {
                return ReturnHelper.successResponselist(res, 200, Language.lang.success_view, 0, current_page, total_count_data, []);
            }

            const packageIds = packages.map((p: any) => p.id);

            // Query 2: all items for these packages (build items[] per package)
            let itemsQuery = OrmHelper.DB.getRepository(DoctorItemPackage)
                .createQueryBuilder("DoctorItemPackage")
                .select([
                    "DoctorItemPackage.id as package_id",
                    "ItemMaster.id as item_id",
                    "ItemMaster.item_name as item_name",
                    "GenericName.generic_name as item_generic_name",
                    "item_type.type_detail_name as item_type",
                    (pharmacyRoomId
                        ? `COALESCE((SELECT SUM(rs.total_stock)::text FROM pharmacy_logistic.room_stock rs WHERE rs."roomId" = :pharmacyRoomId AND rs."itemmasterId" = ItemMaster.id AND rs.deleted_at IS NULL), '0') as pharmacy_stock`
                        : "'0' as pharmacy_stock"),
                    (defaultRoomId
                        ? `COALESCE((SELECT SUM(rs.total_stock)::text FROM pharmacy_logistic.room_stock rs WHERE rs."roomId" = :defaultRoomId AND rs."itemmasterId" = ItemMaster.id AND rs.deleted_at IS NULL), '0') as storage_stock`
                        : "'0' as storage_stock"),
                    "ROUND(CASE WHEN selling_price_percentage.percentage IS NULL " +
                    "THEN COALESCE(item_price.selling_price, 0) " +
                    "ELSE COALESCE(item_price.selling_price, 0) + (COALESCE(item_price.selling_price, 0) * COALESCE(selling_price_percentage.percentage, 0) / 100) END, 2) as price",
                ])
                .leftJoin("DoctorItemPackage.items", "ItemMaster")
                .leftJoin("ItemMaster.generic_name", "GenericName")
                .leftJoin("ItemMaster.type_detail", "item_type")
                .leftJoin(ItemPrice, "item_price", "item_price.item_master_id = ItemMaster.id")
                .leftJoin(SellingPricePercentage, "selling_price_percentage", "selling_price_percentage.item_master_id = ItemMaster.id")
                .where("DoctorItemPackage.id IN (:...ids)", { ids: packageIds });

            if (defaultRoomId) {
                itemsQuery = itemsQuery.setParameter("defaultRoomId", defaultRoomId);
            }
            if (pharmacyRoomId) {
                itemsQuery = itemsQuery.setParameter("pharmacyRoomId", pharmacyRoomId);
            }

            const itemsRaw = await itemsQuery.getRawMany();

            const itemsByPackageId = new Map<string, any[]>();
            for (const row of itemsRaw) {
                const pkgId = row["package_id"];
                if (!pkgId || !row["item_id"]) continue;
                if (!itemsByPackageId.has(pkgId)) itemsByPackageId.set(pkgId, []);
                itemsByPackageId.get(pkgId)!.push({
                    item_id: row["item_id"],
                    item_name: row["item_name"],
                    item_generic_name: row["item_generic_name"],
                    item_type: row["item_type"],
                    pharmacy_stock: row["pharmacy_stock"],
                    storage_stock: row["storage_stock"],
                    price: row["price"],
                });
            }

            const list_data = packages.map((p: any) => ({
                id: p.id,
                name: p.name,
                description: p.description ?? null,
                active: p.active,
                items: itemsByPackageId.get(p.id) ?? [],
            }));

            const count_data = list_data.length;

            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<void | Response> {
        /*
         #swagger.tags = ['Doctor Item Package']
         #swagger.security = [{ "bearerAuth": [] }]
         #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/doctorItemPackage" } } } }
         */
        const queryRunner = OrmHelper.DB.createQueryRunner();
        await queryRunner.startTransaction();
        try {
            const schema = Joi.object().keys({
                doctor_id: Joi.string().uuid().required().label("Doctor ID"),
                name: Joi.string().required().max(256).label("Name"),
                description: Joi.string().allow("", null).optional().label("Description"),
                item_master_ids: Joi.array().items(Joi.string().uuid()).optional().label("Item Master IDs"),
                active: Joi.bool().optional().label("Active"),
            });

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

            const doctor = await OrmHelper.DB.getRepository(User).findOne({ where: { id: param.doctor_id } });
            if (!doctor) throw { message: "Doctor (User) " + Language.lang.failed_not_found };

            // const exist = await DoctorItemPackageModel.list({ "Doctor.id": param.doctor_id, "DoctorItemPackage.name": param.name }).then((q) => q.getOne());
            // if (exist) throw { message: "Doctor Item Package " + Language.lang.failed_duplicate };

            let items: ItemMaster[] = [];
            if (param.item_master_ids && param.item_master_ids.length > 0) {
                for (const itemMasterId of param.item_master_ids) {
                    const itemMaster = await OrmHelper.DB.getRepository(ItemMaster).findOne({ where: { id: itemMasterId } });
                    if (!itemMaster) throw { message: "Item Master " + Language.lang.failed_not_found };
                    items.push(itemMaster);
                }
            }

            let doctorItemPackage = new DoctorItemPackage();
            doctorItemPackage.doctor = doctor;
            doctorItemPackage.name = param.name;
            doctorItemPackage.description = param.description || null;
            doctorItemPackage.items = items;
            doctorItemPackage.active = typeof param.active === "boolean" ? param.active : true;
            doctorItemPackage.created_by = req.auth.data.name;
            doctorItemPackage.updated_by = req.auth.data.name;
            await queryRunner.manager.save(doctorItemPackage);

            await queryRunner.commitTransaction();

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

    static async detail(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
         #swagger.tags = ['Doctor Item Package']
         #swagger.security = [{ "bearerAuth": [] }]
         #swagger.parameters['id'] = { description: '', in: 'path', type: 'string' }
         */
        try {
            const schema = Joi.object().keys({
                id: Joi.string().uuid().required().label("Doctor Item Package Id"),
            });

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

            let doctorItemPackage = await DoctorItemPackageModel.list({ "DoctorItemPackage.id": param.id }).then((q) => q.getOne());

            if (!doctorItemPackage) throw { message: "Doctor Item Package " + Language.lang.failed_not_found };

            return ReturnHelper.successResponseAny(res, 200, Language.lang.success_view, doctorItemPackage);
        } catch (e: unknown) {
            log.error(e);
            const err = e as Error;
            return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_not_found, err.message);
        }
    }

    static async update(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
         #swagger.tags = ['Doctor Item Package']
         #swagger.security = [{ "bearerAuth": [] }]
         #swagger.parameters['id'] = { description: '', in: 'path', type: 'string' }
         #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/doctorItemPackage" } } } }
         */
        const queryRunner = OrmHelper.DB.createQueryRunner();
        await queryRunner.startTransaction();

        try {
            req.body.id = req.params["id"];

            const schema = Joi.object().keys({
                id: Joi.string().uuid().required().label("Doctor Item Package ID"),
                doctor_id: Joi.string().uuid().required().label("Doctor ID"),
                name: Joi.string().required().max(256).label("Name"),
                description: Joi.string().allow("", null).optional().label("Description"),
                item_master_ids: Joi.array().items(Joi.string().uuid()).optional().label("Item Master IDs"),
                active: Joi.bool().optional().label("Active"),
            });

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

            const doctor = await OrmHelper.DB.getRepository(User).findOne({ where: { id: param.doctor_id } });
            if (!doctor) throw { message: "Doctor (User) " + Language.lang.failed_not_found };

            let doctorItemPackage = await DoctorItemPackageModel.list({ "DoctorItemPackage.id": param.id }).then((q) => q.getOne());
            if (!doctorItemPackage) throw { message: "Doctor Item Package " + Language.lang.failed_not_found };

            const exist = await DoctorItemPackageModel.list({ "Doctor.id": param.doctor_id, "DoctorItemPackage.name": param.name }).then((q) => q.getOne());
            if (exist && exist.id != param.id) throw { message: "Doctor Item Package " + Language.lang.failed_duplicate };

            let items: ItemMaster[] = [];
            if (param.item_master_ids && param.item_master_ids.length > 0) {
                for (const itemMasterId of param.item_master_ids) {
                    const itemMaster = await OrmHelper.DB.getRepository(ItemMaster).findOne({ where: { id: itemMasterId } });
                    if (!itemMaster) throw { message: "Item Master " + Language.lang.failed_not_found };
                    items.push(itemMaster);
                }
            }

            doctorItemPackage.doctor = doctor;
            doctorItemPackage.name = param.name;
            doctorItemPackage.description = param.description || null;
            doctorItemPackage.items = items;
            if (typeof param.active === "boolean") {
                doctorItemPackage.active = param.active;
            }
            doctorItemPackage.updated_by = req.auth.data.name;
            await queryRunner.manager.save(doctorItemPackage);

            await queryRunner.commitTransaction();

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

    static async delete(req: Request, res: Response, next: NextFunction): Promise<Response> {
        /*
        #swagger.tags = ['Doctor Item Package']
        #swagger.security = [{ "bearerAuth": [] }]
        #swagger.parameters['id'] = { in: 'path', required: true, type: 'string' }
        */
        try {
            const schema = Joi.object().keys({
                id: Joi.string().uuid().required().label("ID"),
            });

            const param: { id: string } = await schema.validateAsync(req.params);

            const repo = OrmHelper.DB.getRepository(DoctorItemPackage);
            const affected = (await repo.delete({ id: param.id })).affected ?? 0;

            if (affected > 0) {
                return ReturnHelper.successResponseAny(res, 200, Language.lang.success_delete, {});
            } else {
                return ReturnHelper.errorResponse(res, 404, 401, Language.lang.failed_not_found, "");
            }
        } catch (e: unknown) {
            log.error(e);
            const err = e as Error;
            return ReturnHelper.errorResponse(res, 500, 402, Language.lang.failed_delete, err.message);
        }
    }
}
