import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it, vi } from 'vitest';
import {
    AuthProvider,
    buildDefaultProfilePayload,
    shouldCreateDefaultProfile,
    useAuth
} from './AuthContext';

vi.mock('../lib/tradingAuth', () => ({
    TradingAuthProvider: ({ children }: { children: React.ReactNode }) => children,
    useTradingAuth: () => ({
        user: null,
        isLoading: false,
        logout: vi.fn(),
    })
}));

vi.mock('../lib/supabaseClient', () => {
    return {
        supabase: {
            auth: {
                getSession: vi.fn(async () => ({ data: { session: null } })),
                signOut: vi.fn(async () => ({ error: null }))
            }
        }
    };
});

vi.mock('../lib/profileApi', () => ({
    fetchCurrentUserProfile: vi.fn(async () => ({
        user_id: 'user-1',
        first_name: 'User',
        last_name: 'One',
        email: 'user-1@example.com',
        role: 'member',
        trade_enable: true,
    })),
    fetchTradeProfiles: vi.fn(async () => [{ id: 'p1' }]),
}));

describe('AuthContext', () => {
    it('provides auth state through AuthProvider', () => {
        const Probe = () => {
            const auth = useAuth();
            return React.createElement('div', null, auth.loading ? 'loading' : 'ready');
        };

        const html = renderToStaticMarkup(
            React.createElement(AuthProvider, null, React.createElement(Probe))
        );

        expect(html).toContain('loading');
    });

    it('throws when useAuth is called outside provider', () => {
        const BrokenProbe = () => {
            useAuth();
            return React.createElement('div', null, 'never');
        };

        expect(() => renderToStaticMarkup(React.createElement(BrokenProbe))).toThrow(
            'useAuth must be used within an AuthProvider'
        );
    });

    it('detects when default profile must be created', () => {
        expect(shouldCreateDefaultProfile(undefined)).toBe(true);
        expect(shouldCreateDefaultProfile([])).toBe(true);
        expect(shouldCreateDefaultProfile([{ id: 'p1' }])).toBe(false);
    });

    it('builds a deterministic default profile payload', () => {
        const payload = buildDefaultProfilePayload('user-1');

        expect(payload.user_id).toBe('user-1');
        expect(payload.name).toBe('My First Strategy');
        expect(payload.allocated_capital).toBe(1000);
        expect(payload.strategy_config.execution.entryMode).toBe('both');
        expect(payload.strategy_config.rules.some((rule) => rule.ruleId === 'AIAnalysisRule')).toBe(true);
    });
});
