import { createReadStream } from "fs";
import { ApiError } from "../../middleware/ApiError";
import CloudeFormdata from 'form-data'
import axios from "axios";
import { prisma } from "../../utils/prisma";


export class CloudeCacheService {

    private readonly api_email: string;
    private readonly api_key: string;
    private readonly cloude_cache_domain: string


    constructor() {
        this.api_email = process.env.CLOUD_X_AUTH_EMAIL!;
        this.api_key = process.env.CLOUD_X_AUTH_KEY!;
        this.cloude_cache_domain = process.env.CLOUD_CACHE_DOMAIN!;
    }


    // force clear cloud cache

    async clearCloudCache(id: string, token: string) {


        try {
            const response = await axios.post(`${this.cloude_cache_domain}/${token}/purge_cache`,
                {
                    tags: [
                        'a-cache-tag',
                        'another-cache-tag'
                    ]
                },
                {
                    headers: {
                        "X-Auth-Email": this.api_email,
                        "X-Auth-Key": this.api_key
                    }
                })

            return response.data

        } catch (error: any) {
            throw new ApiError("something want wrong with web api", 400)
        }
    }


    async createCloudCache({ token, url, name }: { token: string, url: string, name: string }) {
        const response = await prisma.cloudeCache.create({
            data: {
                url,
                token,
                name
            }
        })
        return response
    }


    async getAllCloudeSite() {
        const response = await prisma.cloudeCache.findMany();
        return response
    }

    async getCloudeSiteById(id: string) {
        const response = await prisma.cloudeCache.findUnique({
            where: {
                id
            }
        });
        return response
    }




    async updateCloudeCache(data: Record<string, string>, id: string) {
        const response = await prisma.cloudeCache.update({
            data,
            where: {
                id
            }
        })
        return response
    }


    async deleteCloudeCache(id: string) {
        const response = await prisma.cloudeCache.delete({
            where: {
                id
            }
        })
        return response
    }


}

export default new CloudeCacheService();