/**
 * Anjaneyulu.in - Authentication & User Management (Server Powered)
 */

const API_BASE = window.location.origin.includes('localhost') || window.location.protocol === 'file:'
    ? "http://localhost:3000/api"
    : `${window.location.origin}/api`;

const Auth = {
    currentUser: null,
    token: null,

    init: () => {
        const stored = localStorage.getItem('anj_current_user');
        const token = localStorage.getItem('anj_token');
        if (stored && token) {
            Auth.currentUser = JSON.parse(stored);
            Auth.token = token;
        }
    },

    requestLoginOTP: async (mobile) => {
        const res = await fetch(`${API_BASE}/auth/request-otp`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ mobile, context: 'login' })
        });
        const data = await res.json();
        // If server says user not found, we handle registration redirect in UI
        if (res.status === 404 || data.code === 'needs_registration') {
            return { status: 'needs_registration' };
        }
        return data;
    },

    requestRegistrationOTP: async (name, mobile) => {
        const res = await fetch(`${API_BASE}/auth/request-otp`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ mobile, name, context: 'register' })
        });
        return await res.json();
    },

    resendOTP: async (mobile) => {
        const res = await fetch(`${API_BASE}/auth/resend-otp`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ mobile })
        });
        return await res.json();
    },

    login: async (mobile, otp) => {
        const res = await fetch(`${API_BASE}/auth/verify-otp`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ mobile, otp, context: 'login' })
        });
        const data = await res.json();
        if (!data.success) throw new Error(data.message || 'Login failed');

        Auth.setCurrentUser(data.user, data.token);
        return data.user;
    },

    register: async (userData) => {
        const res = await fetch(`${API_BASE}/auth/verify-otp`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ ...userData, context: 'register' })
        });
        const data = await res.json();
        if (!data.success) throw new Error(data.message || 'Registration failed');

        Auth.setCurrentUser(data.user, data.token);
        return data.user;
    },

    setCurrentUser: (user, token) => {
        localStorage.setItem('anj_current_user', JSON.stringify(user));
        localStorage.setItem('anj_token', token);
        Auth.currentUser = user;
        Auth.token = token;
    },

    getCurrentUser: () => {
        if (!Auth.currentUser) {
            const stored = localStorage.getItem('anj_current_user');
            if (stored) Auth.currentUser = JSON.parse(stored);
        }
        return Auth.currentUser;
    },

    logout: () => {
        localStorage.removeItem('anj_current_user');
        localStorage.removeItem('anj_token');
        Auth.currentUser = null;
        Auth.token = null;
        window.location.href = 'login.html';
    },

    checkAuth: () => {
        const user = Auth.getCurrentUser();
        if (!user) {
            window.location.href = 'login.html';
        }
        return user;
    },

    checkAdmin: () => {
        const user = Auth.checkAuth();
        if (user.role !== 'admin' && user.role !== 'super_admin') {
            alert('Access Denied: Admins Only');
            window.location.href = 'index.html';
        }
    }
};

// Initialize
Auth.init();

// Maintain legacy UserStore object for compatibility during migration
const UserStore = {
    getUsers: async () => {
        const res = await fetch(`${API_BASE}/users`, {
            headers: { 'Authorization': `Bearer ${Auth.token}` }
        });
        const data = await res.json();
        return data.users || [];
    },
};

const AuditLog = {
    add: async (entry) => {
        console.log('Audit Log:', entry);
        try {
            await fetch(`${API_BASE}/audit`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${Auth.token}`
                },
                body: JSON.stringify(entry)
            });
        } catch (err) {
            console.error('Audit Log failed:', err);
        }
    },
    getAll: async () => {
        try {
            const res = await fetch(`${API_BASE}/audit`, {
                headers: { 'Authorization': `Bearer ${Auth.token}` }
            });
            const data = await res.json();
            return data.logs || [];
        } catch (err) {
            console.error('Failed to fetch audit logs:', err);
            return [];
        }
    }
};
