import { describe, it, expect, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import { MemoryRouter, Routes, Route } from 'react-router-dom'
import { useAuthStore } from '../../../stores/authStore'
import { MustChangePasswordGate } from '../../../components/routing/MustChangePasswordGate'

const adminUser = {
  id: 1,
  username: 'admin',
  nombre: 'Admin',
  rol: 'admin',
  permisos: ['administracion:usuarios:gestionar'],
  mustChangePassword: false,
}

beforeEach(() => {
  useAuthStore.setState({ user: null, accessToken: null, refreshToken: null, expiresAt: null })
})

function renderGate(initialPath: string, mustChangePassword: boolean | null) {
  if (mustChangePassword !== null) {
    useAuthStore.setState({ user: { ...adminUser, mustChangePassword } })
  }

  return render(
    <MemoryRouter initialEntries={[initialPath]}>
      <Routes>
        <Route path="/perfil/contrasena" element={<div>Change Password Page</div>} />
        <Route
          path="*"
          element={
            <MustChangePasswordGate>
              <div>Protected Content</div>
            </MustChangePasswordGate>
          }
        />
      </Routes>
    </MemoryRouter>,
  )
}

describe('MustChangePasswordGate', () => {
  it('redirects to /perfil/contrasena when mustChangePassword=true and on different route', () => {
    renderGate('/usuarios', true)

    expect(screen.getByText('Change Password Page')).toBeInTheDocument()
    expect(screen.queryByText('Protected Content')).not.toBeInTheDocument()
  })

  it('redirects to /perfil/contrasena when mustChangePassword=true on root', () => {
    renderGate('/', true)

    expect(screen.getByText('Change Password Page')).toBeInTheDocument()
    expect(screen.queryByText('Protected Content')).not.toBeInTheDocument()
  })

  it('renders children when mustChangePassword=false', () => {
    renderGate('/usuarios', false)

    expect(screen.getByText('Protected Content')).toBeInTheDocument()
    expect(screen.queryByText('Change Password Page')).not.toBeInTheDocument()
  })

  it('renders children when user is null (let ProtectedRoute handle auth)', () => {
    // user is null — gate should pass through, ProtectedRoute will handle it
    renderGate('/usuarios', null)

    expect(screen.getByText('Protected Content')).toBeInTheDocument()
  })

  it('allows render on /perfil/contrasena when mustChangePassword=true (no redirect loop)', () => {
    useAuthStore.setState({ user: { ...adminUser, mustChangePassword: true } })

    render(
      <MemoryRouter initialEntries={['/perfil/contrasena']}>
        <Routes>
          <Route
            path="/perfil/contrasena"
            element={
              <MustChangePasswordGate>
                <div>Change Password Page Content</div>
              </MustChangePasswordGate>
            }
          />
        </Routes>
      </MemoryRouter>,
    )

    expect(screen.getByText('Change Password Page Content')).toBeInTheDocument()
  })
})
