import { NextFunction, Request, Response } from "express";
import { CatchAsyncError } from "../../middleware/Catch";
import { ApiResponse } from "../../middleware/ApiResponse";
import { ApiError } from "../../middleware/ApiError";
import shopifyService from "./shopify.service";



export const getShopifyCache = CatchAsyncError(async (req: Request, res: Response, next: NextFunction) => {
    const response = await shopifyService.getAllShopify();


    const filterResponse = response.map((e) => {
        if (e.shopifyJsonData) {
            return { ...e, status: true }
        }

        return { ...e, status: false }
    })


    return res.status(200).json(
        new ApiResponse("All Successfully", 200, filterResponse)
    )

})


export const createShopifyCache = CatchAsyncError(async (req: Request, res: Response, next: NextFunction) => {

    const { shopifyId, name } = req.body as { name: string, shopifyId: string }


    const response = await shopifyService.createShopifyCache({ name, shopifyId });
    return res.status(201).json(
        new ApiResponse(`Cache Created Successfully`, 201, [])
    )

});


export const updateShopifyCache = CatchAsyncError(async (req: Request, res: Response, next: NextFunction) => {

    const ShopifyPrimaryID = req.params.shopifyId;


    const findId = await shopifyService.getShopifyById(ShopifyPrimaryID);


    if (!findId) {
        throw new ApiError("Resource not found", 404);
    }

    const { name, shopifyId } = req.body as { name: string, shopifyId: string }

    const response = await shopifyService.updateShopifyCache({ name, shopifyId }, findId.id);

    return res.status(201).json(
        new ApiResponse(`Shopify Updated Successfully`, 201, [])
    )

});






export const deleteShopifyCache = CatchAsyncError(async (req: Request, res: Response, next: NextFunction) => {

    const shopifyId = req.params.shopifyId;

    const findId = await shopifyService.getShopifyById(shopifyId);

    if (!findId) {
        throw new ApiError("Resource not found", 404);
    }

    const response = await shopifyService.deleteShopifyCache(shopifyId);

    return res.status(201).json(
        new ApiResponse(`Shopify Id Deleted Successfully`, 201, [])
    )

});



// todo :clear website cache

export const FetchShopifyCache = CatchAsyncError(async (req: Request, res: Response, next: NextFunction) => {

    const shopifyId = req.params.shopifyId;


    const findId = await shopifyService.getShopifyById(shopifyId);

    if (!findId) {
        throw new ApiError("Resource not found", 404);
    }


    const getProductFromShopify = await shopifyService.FetchShopifyCatch(findId.shopifyId);


    const response = await shopifyService.updateJsonData(getProductFromShopify, findId.id)

    return res.status(201).json(
        new ApiResponse(`Data Has Been Updated`, 201, [])
    )

});


