import { NextFunction, Request, Response } from "express";
import { CatchAsyncError } from "../../middleware/Catch";
import cacheService from "./cache.service";
import { ApiResponse } from "../../middleware/ApiResponse";
import { ApiError } from "../../middleware/ApiError";



export const getCloudeCache = CatchAsyncError(async (req: Request, res: Response, next: NextFunction) => {
    const response = await cacheService.getAllCloudeSite();
    return res.status(200).json(
        new ApiResponse("All Successfully", 200, response)
    )
})


export const createCloudeCache = CatchAsyncError(async (req: Request, res: Response, next: NextFunction) => {

    const { token, url, name } = req.body as { url: string, token: string, name: string }

    const response = await cacheService.createCloudCache({ token, url, name });
    return res.status(201).json(
        new ApiResponse(`Cache Created Successfully`, 201, [])
    )

});


export const updateCloudeCache = CatchAsyncError(async (req: Request, res: Response, next: NextFunction) => {

    const cacheId = req.params.cacheId;


    const findId = await cacheService.getCloudeSiteById(cacheId);


    if (!findId) {
        throw new ApiError("Resource not found", 404);
    }

    const { token, url, name } = req.body as { url: string, token: string, name: string }

    const response = await cacheService.updateCloudeCache({ token, name }, cacheId);

    return res.status(201).json(
        new ApiResponse(`Cache Updated Successfully`, 201, [])
    )

});






export const deleteCloudeCache = CatchAsyncError(async (req: Request, res: Response, next: NextFunction) => {

    const cacheId = req.params.cacheId;


    const findId = await cacheService.getCloudeSiteById(cacheId);

    if (!findId) {
        throw new ApiError("Resource not found", 404);
    }

    const response = await cacheService.deleteCloudeCache(cacheId);

    return res.status(201).json(
        new ApiResponse(`Cache Deleted Successfully`, 201, [])
    )

});



// todo :clear website cache

export const forceClearCloudeCache = CatchAsyncError(async (req: Request, res: Response, next: NextFunction) => {

    const cacheId = req.params.cacheId;


    const findId = await cacheService.getCloudeSiteById(cacheId);

    if (!findId) {
        throw new ApiError("Resource not found", 404);
    }


    const response = await cacheService.clearCloudCache(findId.id, findId.token);


    return res.status(201).json(
        new ApiResponse(`Cache clear - ${findId.name} `, 201, response)
    )

});


