import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, fireEvent, waitFor } from '@testing-library/react';
import { renderWithProviders } from '../test/utils';

vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
vi.mock('../lib/api', () => ({
  api: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), put: vi.fn(), delete: vi.fn() },
  ApiError: class extends Error {},
}));

import { api } from '../lib/api';
import { useAuthStore } from '../stores/authStore';
import AccountSettingsPage from './AccountSettingsPage';

const post = api.post as ReturnType<typeof vi.fn>;

beforeEach(() => {
  post.mockReset();
  post.mockResolvedValue({ success: true, data: { message: 'ok' } });
  useAuthStore.setState({ primaryRole: 'doctor', userName: 'دکتر امینی', context: null });
});

describe('AccountSettingsPage', () => {
  it('shows the profile summary and change-password form in the settings shell', () => {
    renderWithProviders(<AccountSettingsPage />, { route: '/admin/account-settings' });
    expect(screen.getByText('خرید اشتراک')).toBeInTheDocument();        // shell menu
    expect(screen.getAllByText('دکتر امینی').length).toBeGreaterThan(0); // profile name
    expect(screen.getAllByText('تغییر رمز عبور').length).toBeGreaterThan(0); // heading + button
  });

  it('submits the change-password request with current + new password', async () => {
    renderWithProviders(<AccountSettingsPage />, { route: '/admin/account-settings' });

    fireEvent.change(screen.getByLabelText('رمز فعلی'), { target: { value: 'oldpass12' } });
    fireEvent.change(screen.getByLabelText('رمز جدید'), { target: { value: 'newpass34' } });
    fireEvent.change(screen.getByLabelText('تکرار رمز جدید'), { target: { value: 'newpass34' } });
    fireEvent.click(screen.getByRole('button', { name: 'تغییر رمز عبور' }));

    await waitFor(() => expect(post).toHaveBeenCalledWith('/api/v1/user/change-password', {
      current_password: 'oldpass12', new_password: 'newpass34',
    }));
  });

  it('blocks submit when the confirmation does not match', async () => {
    renderWithProviders(<AccountSettingsPage />, { route: '/admin/account-settings' });

    fireEvent.change(screen.getByLabelText('رمز فعلی'), { target: { value: 'oldpass12' } });
    fireEvent.change(screen.getByLabelText('رمز جدید'), { target: { value: 'newpass34' } });
    fireEvent.change(screen.getByLabelText('تکرار رمز جدید'), { target: { value: 'different' } });
    fireEvent.click(screen.getByRole('button', { name: 'تغییر رمز عبور' }));

    expect(await screen.findByText('تکرار رمز مطابقت ندارد')).toBeInTheDocument();
    expect(post).not.toHaveBeenCalled();
  });
});
