import { ref, type Ref, type App } from 'vue';

class Cookie {
  private items: Ref<Map<any, any>> = ref(new Map());

  constructor() {
    const stringified: string = document.cookie;
    if (stringified?.length) {
      const splitted = stringified.split('; ')
      for (const cookie of splitted) {
        const [key, value] = cookie.split('=')
        this.items.value.set(key, value)
      }
    }
  }

  public has(key: string): boolean {
    return this.items.value.has(key);
  }

  public get(key: string): any {
    return this.items.value.get(key);
  }

  public set(key: string, value: any): void {
    this.items.value.set(key, value);
    document.cookie = `${key}=${value}; Secure`;
  }

  public remove(key: string): void {
    this.items.value.delete(key);
    document.cookie =
      `${key}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Secure`;
  }
}

export const $cookie: Cookie = new Cookie()

export default {
  install: (app: App) => {
    app.config.globalProperties.$cookie = $cookie;
  },
};
