import { createReadStream } from "fs";
import { ApiError } from "../../middleware/ApiError";
import CloudeFormdata from 'form-data'
import axios from "axios";
import { prisma } from "../../utils/prisma";
import { JsonValue } from "@prisma/client/runtime/library";


export class ShopifyCacheService {

    private readonly api_email: string;
    private readonly api_key: string;
    private readonly shopify_cache_domain: string
    private readonly shopify_access_token: string


    constructor() {
        this.api_email = process.env.CLOUD_X_AUTH_EMAIL!;
        this.api_key = process.env.CLOUD_X_AUTH_KEY!;
        this.shopify_cache_domain = process.env.SHOPIFY_CACHE_DOMAIN!;
        this.shopify_access_token = process.env.SHOPIFY_ACCESS_TOKEN as string
    }

    // fetch shopify cache data


    async FetchShopifyCatch(id?: string) {
        const response = await axios.get(this.shopify_cache_domain, {
            params: {
                ids: id
            },
            headers: {
                "X-Shopify-Access-Token": this.shopify_access_token
            }
        })
        return response.data
    }




    async createShopifyCache({ name, shopifyId }: { shopifyId: string, name: string }) {
        const response = await prisma.shopify.create({
            data: {
                name,
                shopifyId
            }
        })
        return response
    }


    async getAllShopify() {
        const response = await prisma.shopify.findMany();
        return response
    }

    async getShopifyById(id: string) {
        const response = await prisma.shopify.findUnique({
            where: {
                id
            }
        });
        return response
    }




    async updateShopifyCache(data: Record<string, string>, id: string) {
        const response = await prisma.shopify.update({
            data,
            where: {
                id
            }
        })
        return response
    }


    async deleteShopifyCache(id: string) {
        const response = await prisma.shopify.delete({
            where: {
                id
            }
        })
        return response
    }


    // todo:update json data


    async updateJsonData(data: JsonValue, id: string) {

        const response = await prisma.shopify.update({
            data: {
                shopifyJsonData: JSON.stringify(data)
            },
            where: {
                id
            }
        })

        return response
    }



}

export default new ShopifyCacheService();