import { setCookie, parseCookies, destroyCookie } from 'nookies';

export interface UserSession {
  id?: string;
  name?: string;
  phone?: string;
  email?: string;
  avatar?: string;
  access_token?: string;
}

export const AUTH_COOKIES = {
  FOOD: 'COOKIES_USER_ACCESS_TOKEN',
  CAB: 'cookies_user_access_token',
  CAB_TEMP: 'cookies_user_access_token_temp',
  FOOD_TEMP: 'TEMP_COOKIES_USER_ACCESS_TOKEN',
};

export function savePlatformSession(token: string, user?: any) {
  if (!token) return;

  const cookieOptions = {
    maxAge: 30 * 24 * 60 * 60,
    path: '/',
    sameSite: 'lax' as const,
    secure: typeof window !== 'undefined' ? window.location.protocol === 'https:' : false,
  };

  // Sync cookies for both Food (Next) and Cab (React)
  setCookie(null, AUTH_COOKIES.FOOD, token, cookieOptions);
  setCookie(null, AUTH_COOKIES.CAB, token, cookieOptions);

  if (typeof window !== 'undefined') {
    try {
      sessionStorage.setItem('token', token);
      localStorage.setItem('auth_token', token);
      if (user) {
        localStorage.setItem('user_profile', JSON.stringify(user));
      }
      window.dispatchEvent(new CustomEvent('READY_MFE_EVENT', {
        detail: { type: 'MFE_AUTH_LOGIN', payload: { token, user } }
      }));
    } catch (e) {}
  }
}

export function clearPlatformSession() {
  destroyCookie(null, AUTH_COOKIES.FOOD, { path: '/' });
  destroyCookie(null, AUTH_COOKIES.CAB, { path: '/' });
  destroyCookie(null, AUTH_COOKIES.CAB_TEMP, { path: '/' });
  destroyCookie(null, AUTH_COOKIES.FOOD_TEMP, { path: '/' });

  if (typeof window !== 'undefined') {
    try {
      sessionStorage.clear();
      localStorage.removeItem('auth_token');
      localStorage.removeItem('user_profile');
      window.dispatchEvent(new CustomEvent('READY_MFE_EVENT', {
        detail: { type: 'MFE_LOGOUT' }
      }));
    } catch (e) {}
  }
}

export function getPlatformToken(): string | null {
  const cookies = parseCookies();
  const token = cookies[AUTH_COOKIES.FOOD] || cookies[AUTH_COOKIES.CAB];
  if (token) return token;

  if (typeof window !== 'undefined') {
    return sessionStorage.getItem('token') || localStorage.getItem('auth_token');
  }
  return null;
}
