import { redirect } from "@/i18n";
import { Response } from "@/types";
import { cookies } from "next/headers";
import { ServerOptions } from "./type";

import { locales } from "@/i18n";
const requestInterceptor = (options: ServerOptions) => {
    // 判断token
    if (options.checkToken) {
        const token = cookies().has("Token");
        if (!token) {
            redirect("/login");
        }
    }
    return options;
};
const responseInterceptor = <T = any, R = unknown>(
    response: Response<T> & R,
    options: ServerOptions
): Promise<Response<T> & R> => {
    return new Promise((resolve, reject) => {
        const { code, msg } = response;
        switch (code) {
            case 200:
                resolve(response);
                break;
            case 401:
                console.log(`🚀🚀🚀🚀🚀->server-code: 401`, options.url);
                redirect("/login");
                break;
            default:
                console.log({
                    ...response,
                    message: `please check api ${options.url}`,
                });
                reject(response);
        }
    });
};
class Server {
    private static instance: Server;
    private BASE_URL: string;
    constructor() {
        this.BASE_URL = process.env.NEXT_PUBLIC_BASE_URL as string;
    }

    async request<T, R = unknown>(options: ServerOptions): Promise<Response<T> & R> {
        options = requestInterceptor(options);
        const { method = "GET", url, headers = {}, data = {}, body, ...other } = options;
        const params = JSON.stringify(data);
        try {
            const response = await fetch(`${this.BASE_URL}${url}`, {
                method: method,
                headers: {
                    Token: cookies().get("Token")?.value || "",
                    "Content-Type": "application/json",
                    language:
                        cookies().get("language")?.value === "br"
                            ? "pt"
                            : cookies().get("language")?.value || locales.at(2)!,
                    ...headers,
                },
                body: params,
                ...other,
            }).then((res) => res.json());
            return responseInterceptor<T, R>(response, options);
        } catch (error) {
            return Promise.reject(error);
        }
    }
}

export const server = new Server();
