// ====== Authentication Helpers ======

import { STORAGE_KEYS, ERROR_MESSAGES } from '../config/constants.js';
import { showNotification } from './helpers.js';

class AuthManager {
    constructor() {
        this.token = this.getStoredToken();
        this.user = this.getStoredUser();
    }

    // Token management
    getStoredToken() {
        return localStorage.getItem(STORAGE_KEYS.AUTH_TOKEN) || 
               sessionStorage.getItem(STORAGE_KEYS.AUTH_TOKEN);
    }

    setToken(token, rememberMe = false) {
        this.token = token;
        const storage = rememberMe ? localStorage : sessionStorage;
        storage.setItem(STORAGE_KEYS.AUTH_TOKEN, token);
    }

    removeToken() {
        this.token = null;
        localStorage.removeItem(STORAGE_KEYS.AUTH_TOKEN);
        sessionStorage.removeItem(STORAGE_KEYS.AUTH_TOKEN);
    }

    // User management
    getStoredUser() {
        const userData = localStorage.getItem(STORAGE_KEYS.USER_DATA) || 
                        sessionStorage.getItem(STORAGE_KEYS.USER_DATA);
        return userData ? JSON.parse(userData) : null;
    }

    setUser(user, rememberMe = false) {
        this.user = user;
        const storage = rememberMe ? localStorage : sessionStorage;
        storage.setItem(STORAGE_KEYS.USER_DATA, JSON.stringify(user));
    }

    removeUser() {
        this.user = null;
        localStorage.removeItem(STORAGE_KEYS.USER_DATA);
        sessionStorage.removeItem(STORAGE_KEYS.USER_DATA);
    }

    // Authentication status
    isAuthenticated() {
        return !!this.token && !!this.user;
    }

    hasRole(role) {
        return this.isAuthenticated() && this.user.role === role;
    }

    hasPermission(permission) {
        return this.isAuthenticated() && 
               this.user.permissions && 
               this.user.permissions.includes(permission);
    }

    // Login/Logout
    async login(credentials, rememberMe = false) {
        try {
            const response = await fetch('/api/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(credentials)
            });

            if (!response.ok) {
                throw new Error(ERROR_MESSAGES.AUTH_ERROR);
            }

            const data = await response.json();
            
            this.setToken(data.token, rememberMe);
            this.setUser(data.user, rememberMe);
            
            showNotification('Login successful!', 'success');
            return data;
            
        } catch (error) {
            showNotification(error.message, 'error');
            throw error;
        }
    }

    async logout() {
        try {
            // Call logout endpoint if token exists
            if (this.token) {
                await fetch('/api/auth/logout', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${this.token}`
                    }
                });
            }
        } catch (error) {
            console.warn('Logout API call failed:', error);
        } finally {
            this.removeToken();
            this.removeUser();
            showNotification('Logged out successfully', 'info');
            
            // Redirect to login page
            window.location.href = '/login';
        }
    }

    // Password strength checker
    checkPasswordStrength(password) {
        const checks = {
            length: password.length >= 8,
            uppercase: /[A-Z]/.test(password),
            lowercase: /[a-z]/.test(password),
            number: /\d/.test(password),
            special: /[!@#$%^&*(),.?":{}|<>]/.test(password)
        };

        const score = Object.values(checks).filter(Boolean).length;
        
        return {
            score,
            checks,
            strength: score <= 2 ? 'weak' : score <= 3 ? 'medium' : score <= 4 ? 'strong' : 'very-strong'
        };
    }
}

// Create singleton instance
export const authManager = new AuthManager();