import { ref } from 'vue'

export interface LoginResponse {
  success: boolean
  userId?: string
  token?: string
  error?: string
}

export interface SessionData {
  user: {
    id: string
    email: string
    name?: string
  }
  session: {
    token: string
    expiresAt: string
  }
}

const TOKEN_STORAGE_KEY = 'dexorder_auth_token'

class AuthService {
  public isAuthenticated = ref(false)
  private token: string | null = null
  private gatewayUrl: string

  constructor() {
    // Use environment variable for gateway URL, fallback based on current location
    // VITE_GATEWAY_URL can be:
    //   - Relative path: "/api" (for production with ingress)
    //   - Absolute URL: "http://localhost:3000" (for local dev)
    //   - Absolute URL: "http://dexorder.local" (for minikube)
    const envUrl = import.meta.env.VITE_GATEWAY_URL

    if (envUrl) {
      // If it starts with /, it's a relative path - use current origin
      if (envUrl.startsWith('/')) {
        this.gatewayUrl = window.location.origin + envUrl
      } else {
        this.gatewayUrl = envUrl
      }
    } else if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
      // Local development default
      this.gatewayUrl = 'http://localhost:3000'
    } else {
      // Production default: use current origin
      this.gatewayUrl = window.location.origin
    }

    // Try to restore token from localStorage
    const storedToken = localStorage.getItem(TOKEN_STORAGE_KEY)
    if (storedToken) {
      this.token = storedToken
      this.isAuthenticated.value = true
    }
  }

  /**
   * Login with email and password
   */
  async login(email: string, password: string): Promise<LoginResponse> {
    try {
      const response = await fetch(`${this.gatewayUrl}/auth/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email, password }),
      })

      // Check if response is JSON before parsing
      const contentType = response.headers.get('content-type')
      if (!contentType || !contentType.includes('application/json')) {
        return {
          success: false,
          error: `Server error (${response.status}): ${response.statusText || 'Service unavailable'}`,
        }
      }

      const data = await response.json()

      if (!response.ok) {
        return {
          success: false,
          error: data.error || 'Login failed',
        }
      }

      if (data.success && data.token) {
        this.token = data.token
        localStorage.setItem(TOKEN_STORAGE_KEY, data.token)
        this.isAuthenticated.value = true

        return {
          success: true,
          userId: data.userId,
          token: data.token,
        }
      }

      return {
        success: false,
        error: 'Invalid response from server',
      }
    } catch (error: any) {
      console.error('Login error:', error)
      return {
        success: false,
        error: error.message || 'Network error',
      }
    }
  }

  /**
   * Logout and clear session
   */
  async logout(): Promise<void> {
    try {
      if (this.token) {
        await fetch(`${this.gatewayUrl}/auth/logout`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${this.token}`,
          },
        })
      }
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      this.token = null
      localStorage.removeItem(TOKEN_STORAGE_KEY)
      this.isAuthenticated.value = false
    }
  }

  /**
   * Get current session information
   */
  async getSession(): Promise<SessionData | null> {
    if (!this.token) {
      return null
    }

    try {
      const response = await fetch(`${this.gatewayUrl}/auth/session`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${this.token}`,
        },
      })

      if (!response.ok) {
        // Token is invalid or expired
        this.token = null
        localStorage.removeItem(TOKEN_STORAGE_KEY)
        this.isAuthenticated.value = false
        return null
      }

      const data = await response.json()
      return data
    } catch (error) {
      console.error('Get session error:', error)
      return null
    }
  }

  /**
   * Get the current auth token
   */
  getToken(): string | null {
    return this.token
  }

  /**
   * Check if user is authenticated by verifying session
   */
  async checkAuth(): Promise<boolean> {
    const session = await this.getSession()
    return session !== null
  }
}

export const authService = new AuthService()
