import { isPlatformBrowser } from '@angular/common';
import { inject, Injectable, PLATFORM_ID, REQUEST } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Injectable({
  providedIn: 'root'
})
export class CookieService {
  private readonly platformId = inject(PLATFORM_ID);
  private readonly document = inject(DOCUMENT);
  private readonly request = inject(REQUEST, { optional: true });

  get(name: string): string | null {
    if (isPlatformBrowser(this.platformId)) {
      return this.getCookieFromString(name, this.document.cookie);
    }

    if (this.request) {
      const cookieHeader = this.request.headers.get('cookie') || '';
      return this.getCookieFromString(name, cookieHeader);
    }

    return null;
  }

  set(name: string, value: string, days = 7): void {
    if (isPlatformBrowser(this.platformId)) {
      const date = new Date();
      date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
      const expires = `expires=${date.toUTCString()}`;
      this.document.cookie = `${name}=${value};${expires};path=/;SameSite=Lax`;
    }
  }

  delete(name: string): void {
    if (isPlatformBrowser(this.platformId)) {
      this.document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;SameSite=Lax`;
    }
  }

  private getCookieFromString(name: string, cookieString: string): string | null {
    if (!cookieString) {
      return null;
    }
    
    const nameEQ = `${name}=`;
    const ca = cookieString.split(';');
    for (let i = 0; i < ca.length; i++) {
      let c = ca[i];
      while (c.charAt(0) === ' ') {
        c = c.substring(1, c.length);
      }
      if (c.indexOf(nameEQ) === 0) {
        return c.substring(nameEQ.length, c.length);
      }
    }
    return null;
  }
}
