import Redis from "ioredis";
import { initClient } from './utils.js';

const redis = new Redis({
    host: 'redis-12291.c305.ap-south-1-1.ec2.cloud.redislabs.com',
    port: 12291,
    password: 'KQCVapXXF2ioM4zF5krQFImzAYkKWY5l',
    username: "default"  // Replace with your Redis instance's password
});



export const getCompanyCreds = async ({ company_id }) => {
    const creds = await redis.get(`${company_id}:creds`);
    if (!creds) {
        throw {
            message: "company creds not found"
        }
    }
    return { ...JSON.parse(creds), company_id }
}
export const createUpdateCompanyCreds = async ({ company_id, clientId, clientSecret }) => {
    const creds = await redis.set(`${company_id}:creds`, JSON.stringify({ clientId, clientSecret }));
    return { message: "company creds saved" }
}
export const getApplications = async ({ company_id }) => {
    const client = await initClient(company_id);
    let applications = await client.configuration.getApplications({ pageSize: 100 });
    applications = applications.items.map(i => {
        return {
            name: i.name,
            id: i.id,
            token: i.token,
            domain: i.domains?.find(i => i.is_primary)?.name,
            logo: i.logo?.secure_url
        }
    })
    return applications;
}
export const createBrand = async ({ company_id, name, description, logo = "https://cdn.pixelbin.io/v2/falling-surf-7c8bb8/fyprod/wrkr/platform/pictures/favicon/original/ZWTmgEoFQ-platform-favicon.png" }) => {
    const client = await initClient(company_id);
    let brands = await client.companyProfile.createBrand({
        body: {
            name,
            description,
            logo,
            banner: { portrait: logo, landscape: logo }
        }
    });
    return { message: "brand created", id: brands?.uid };
}
export const getBrands = async ({ company_id }) => {
    const client = await initClient(company_id);
    let brands = await client.companyProfile.getBrands({ pageSize: 300 });
    brands = brands.items.map(i => {
        return {
            name: i?.brand?.name,
            logo: i?.brand?.logo,
            id: i?.brand?.uid,
        }
    })
    return brands
}
export const updateBrand = async ({ company_id, brand_id }) => {
    const client = await initClient(company_id);
    let brands = await client.companyProfile.editBrand({
        brand_id,
        body: {
            name,
            description,
            logo,
            banner: { portrait: logo, landscape: logo }
        }
    });
    return { message: "brand updated" }
}

export const getLocations = async ({ company_id }) => {
    const client = await initClient(company_id);
    let locations = await client.companyProfile.getLocations({ pageSize: 100 });
    locations = locations.items.map(i => {
        return {
            name: i.name,
            id: i.uid,
            code: i.code,
            documents: i.documents
        }
    })
    return locations;
}
export const createLocation = async ({ name, company_id, address1, address2, pincode, state, city, country, number, country_code, gst_name, gst_no, latitude = 19.2762702, longitude = 72.8929, code, manager_name, email }) => {
    const client = await initClient(company_id);
    let locations = await client.companyProfile.createLocation({
        body: {
            name,
            display_name: name,
            code,
            company: parseInt(company_id),
            documents: [{
                type: "gst",
                legal_name: gst_name,
                value: gst_no,
                verified: true
            }],
            address: {
                "address1": address1,
                "address2": address2,
                "country": country,
                "pincode": pincode,
                "city": city,
                "state": state,
                "latitude": latitude,
                "longitude": longitude,
                "landmark": ''
            },
            manager: {
                "name": manager_name,
                "email": email,
                "mobile_no": {
                    "number": number,
                    "country_code": country_code
                }
            },
            contact_numbers: [
                {
                    "number": number,
                    "country_code": country_code
                }
            ],
            store_type: "high_street"

        }
    });

    return { message: "location added", id: locations?.uid };
}
export const updateLocation = async ({ company_id, location_id, address1, address2, pincode, state, city, number, country_code, gst_name, gst_no, latitude = 19.2762702, longitude = 72.8929,
}) => {
    const client = await initClient(company_id);
    let locations = await client.companyProfile.updateLocation({
        locationId: location_id,
        body: {
            name,
            display_name: name,
            code,
            company: parseInt(companyId),
            documents: [{
                type: "gst",
                legal_name: gst_name,
                value: gst_no,
                verified: true
            }],
            address: {
                "address1": address1,
                "address2": address2,
                "country": country,
                "pincode": pincode,
                "city": city,
                "state": state,
                "latitude": latitude,
                "longitude": longitude,
                "landmark": landmark
            },
            manager: {
                "name": manager_name,
                "email": email,
                "mobile_no": {
                    "number": number,
                    "country_code": country_code
                }
            },
            contact_numbers: [
                {
                    "number": number,
                    "country_code": country_code
                }
            ],
            store_type: "high_street"

        }
    });

    return { message: "location updated" };
}
export const createApplication = async ({ company_id, brand_ids, name, subdomain }) => {
    const client = await initClient(company_id);
    let app = await client.configuration.createApplication({
        body: {
            "app": {
                "company_id": (1).toString(),
                "channel_type": "website-and-mobile-apps",
                "auth": {
                    "enabled": true
                },
                "name": name,
                "desc": "",
                "mode": "live"
            },
            "configuration": {
                "inventory": {
                    "brand": {
                        "criteria": "all",
                        "brands": []
                    },
                    "store": {
                        "criteria": "filter",
                        "rules": [
                            {
                                "companies": [company_id],
                                "brands": brand_ids
                            }
                        ],
                        "stores": []
                    },
                    "image": ["standard", "substandard", "default"],
                    "franchise_enabled": false,
                    "out_of_stock": true
                },
                "payment": {
                    "mode_of_payment": "ECOMM",
                    "source": "ECOMM"
                },
                "article_assignment": {
                    "post_order_reassignment": true,
                    "enforced_stores": [],
                    "rules": {
                        "store_priority": {
                            "enabled": false,
                            "storetype_order": []
                        }
                    }
                }
            },
            "domain": {
                "name": `${subdomain}.hostx5.de`
            }
        }
    })


    return { ...app };
}
export const createProduct = async ({ name, company_id, slug,
    seller_identifier,
    brand_id, mrp = 999, selling_price = 499 }) => {
    const client = await initClient(company_id);
    const obj = {
        "name": name,
        "slug": slug,
        "brand_uid": brand_id,
        "item_code": seller_identifier,
        "teaser_tag": {},
        "net_quantity": {},
        "tax_identifier": {
            "reporting_hsn": "1202355241H1",
            "hsn_code": "1202355241",
            "hsn_code_id": "65769883ba99dcf407a2b1ed"
        },
        "country_of_origin": "India",
        "variants": {},
        "variant_media": {},
        "description": "PHA+WW91ciBwcm9kdWN0IGRlc2NyaXB0aW9uPC9wPg==",
        "short_description": "Your product description",
        "highlights": [],
        "company_id": 10,
        "template_tag": "c2-0-template",
        "currency": "INR",
        "media": [],
        "is_set": false,
        "sizes": [
            {
                "size": "OS",
                "price": mrp,
                "price_effective": selling_price,
                "price_transfer": 0,
                "currency": "INR",
                "item_length": 1,
                "item_width": 1,
                "item_height": 1,
                "item_weight": 1,
                "item_dimensions_unit_of_measure": "cm",
                "item_weight_unit_of_measure": "gram",
                "track_inventory": true,
                "identifiers": [
                    {
                        "gtin_value": seller_identifier,
                        "gtin_type": "ean",
                        "primary": true
                    }
                ],
                "_custom_json": {},
                "name": "OS"
            }
        ],
        "_custom_json": {},
        "size_guide": "",
        "product_group_tag": [],
        "product_publish": {
            "product_online_date": "2023-12-11T08:38:10.082Z",
            "is_set": false
        },
        "is_active": true,
        "custom_order": {
            "is_custom_order": false,
            "manufacturing_time": 0,
            "manufacturing_time_unit": "hours"
        },
        "multi_size": false,
        "no_of_boxes": 1,
        "is_dependent": false,
        "item_type": "digital",
        "tags": [],
        "departments": [
            19771
        ],
        return_config: {
            "returnable": false
        },
        "category_slug": "c2-0-cat",
        "trader": [
            {
                "type": "Manufacturer",
                "name": "Manufacturer",
                "address": [
                    "Manufacturer Address"
                ]
            }
        ],
        "return_config": {
            "returnable": true,
            time: 3,
            unit: "days"
        }
    }
    let product = await client.catalog.createProduct({
        body: obj
    });
    product = await client.catalog.getProduct({
        itemId: product.uid
    });
    return {
        message: "product created",
        id: product.data.uid,
        seller_identifier: product?.data?.sizes?.[0]?.seller_identifier
    };
}
export const createInventory = async ({ company_id, product_id, seller_identifier, location_id, mrp = 999, selling_price = 499 }) => {
    const client = await initClient(company_id);
    let product = await client.catalog.getProduct({
        itemId: product_id
    });
    let inv = await client.catalog.updateRealtimeInventory({
        itemId: product.data.uid,
        sellerIdentifier: seller_identifier,
        body: {
            company_id: company_id,
            payload: [{
                "seller_identifier": seller_identifier,
                "store_id": location_id,
                "price_marked": mrp,
                "price_effective": selling_price,
                "total_quantity": 10,
                "tags": []
            }]
        }
    })

    return { message: "inv created" };
}