// Payload CMS Authentication Service
// Handles authentication with Payload CMS backend

// Get API base URL from wrangler.toml configuration
function getApiBaseUrl() {
  // Check for environment-specific URLs from wrangler.toml
  if (typeof process !== 'undefined' && process.env) {
    return process.env.PAYLOAD_CMS_URL;
  }
  // Fallback for client-side or when process.env is not available
  return import.meta.env.PUBLIC_PAYLOAD_CMS_URL || 'https://enchun-admin.anlstudio.cc';
}

const PAYLOAD_URL = getApiBaseUrl();
const PAYLOAD_API_KEY = import.meta.env.PAYLOAD_CMS_API_KEY;

export interface User {
  id: string;
  email: string;
  role: 'admin' | 'editor';
}

export interface AuthResponse {
  user: User;
  token: string;
}

export class AuthService {
  private token: string | null = null;

  constructor() {
    // Load token from localStorage or cookie on client
    if (typeof window !== 'undefined') {
      this.token = localStorage.getItem('payload-token');
    }
  }

  async login(email: string, password: string): Promise<AuthResponse> {
    const response = await fetch(`${PAYLOAD_URL}/api/users/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(PAYLOAD_API_KEY && { 'Authorization': `Bearer ${PAYLOAD_API_KEY}` }),
      },
      body: JSON.stringify({ email, password }),
    });

    if (!response.ok) {
      throw new Error('Login failed');
    }

    const data: AuthResponse = await response.json();
    this.token = data.token;

    // Store token
    if (typeof window !== 'undefined') {
      localStorage.setItem('payload-token', data.token);
    }

    return data;
  }

  async logout(): Promise<void> {
    const tokenForRequest = this.token;
    this.token = null;
    if (typeof window !== 'undefined') {
      localStorage.removeItem('payload-token');
    }

    // Optional: Call logout endpoint
    try {
      const headers: Record<string, string> = {
        'Content-Type': 'application/json',
      };
      if (tokenForRequest) {
        headers['Authorization'] = `Bearer ${tokenForRequest}`;
      }
      await fetch(`${PAYLOAD_URL}/api/users/logout`, {
        method: 'POST',
        headers,
      });
    } catch (error) {
      // Ignore logout errors
    }
  }

  setToken(token: string): void {
    this.token = token;
  }

  async getCurrentUser(): Promise<User | null> {
    if (!this.token) return null;

    try {
      const response = await fetch(`${PAYLOAD_URL}/api/users/me`, {
        headers: {
          'Authorization': `Bearer ${this.token}`,
        },
      });

      if (!response.ok) {
        this.token = null;
        return null;
      }

      const data = await response.json();
      return data.user;
    } catch (error) {
      this.token = null;
      return null;
    }
  }

  getToken(): string | null {
    return this.token;
  }

  isAuthenticated(): boolean {
    return !!this.token;
  }
}

export const authService = new AuthService();