import { Router, type Request, type Response } from "express";
import { prodQuery } from "../../../pkg/prodSql/prodQuery.js";
import { tryCatch } from "../../../pkg/utils/tryCatch.js";
import { db } from "../../../pkg/db/db.js";
import { settings } from "../../../pkg/db/schema/settings.js";
import { eq } from "drizzle-orm";
import { activeArticle } from "../../../pkg/prodSql/querys/datamart/article.js";

type Articles = {
article: string
description: string
articleType: string
pricePoint:string
salesPrice:string
typeOfMaterial:string
articleIdType:string
articleWeight:string
idAddress:string
addressDescription:string
addressType:string
profitCenter:String
fg: string
num_of_cycles:string
costsCenterId:string
costCenterDescription:string
customerArticleNumber:string
customerArticleDescription:String
cycleTime:string
salesAgreement:string
productFamily:string
uom:string
}


const router = Router();

// GET /health
router.get("/", async (req: Request, res: Response) => {

    const includePlantToken = req.params.includePlantToken
    
    let articles:Articles[] = [];
        try {
            const res = await prodQuery(activeArticle, "Get active articles");
            articles = res?.data;
        }
        catch (error) {
            return {
                    success: false,
                    message:"Error getting articles",
                    error: error
                };
        }
        if (includePlantToken) {
            const { data, error } = await tryCatch(db.select().from(settings).where(eq(settings.name, "plantToken")))
            if (error) {
                
                return {
                    success: false,
                    message:"Error getting settings",
                    error: error
                };
            }
            // return articles.map((n) => {
            //     return {
            //         success: true,
            //         message: "Active articles including plant token",
            //         data:{ plantToken: data[0].value, ...n }};
            // });

            return {
                success: true,
                message: "Active articles including plant token",
                data: articles.map((n) => {
                    return { plantToken: data[0].value, ...n }
                })
            }
        }
        else {
            return {
                    success: true,
                    message: "Active articles including plant token",
                    data:articles};
        }


});

export default router;