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 { ProtectedRoute } from '../../../components/routing/ProtectedRoute'

// Helper components for testing
function SecurePage() {
  return <div>Secure Page</div>
}

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

describe('ProtectedRoute', () => {
  it('F-03-01: sin user → redirect a /login', () => {
    useAuthStore.setState({ user: null })

    render(
      <MemoryRouter initialEntries={['/secure']}>
        <Routes>
          <Route path="/login" element={<div>Login Page</div>} />
          <Route
            path="/secure"
            element={
              <ProtectedRoute>
                <SecurePage />
              </ProtectedRoute>
            }
          />
        </Routes>
      </MemoryRouter>,
    )

    expect(screen.getByText('Login Page')).toBeInTheDocument()
    expect(screen.queryByText('Secure Page')).not.toBeInTheDocument()
  })

  it('F-03-02: user autenticado sin restricciones → renderiza children', () => {
    useAuthStore.setState({
      user: { id: 2, username: 'cajero', nombre: 'Cajero', rol: 'cajero', permisos: [], mustChangePassword: false },
    })

    render(
      <MemoryRouter initialEntries={['/secure']}>
        <Routes>
          <Route path="/login" element={<div>Login Page</div>} />
          <Route
            path="/secure"
            element={
              <ProtectedRoute>
                <SecurePage />
              </ProtectedRoute>
            }
          />
        </Routes>
      </MemoryRouter>,
    )

    expect(screen.getByText('Secure Page')).toBeInTheDocument()
  })

  it('F-03-03: requiredRoles coincide → renderiza children', () => {
    useAuthStore.setState({
      user: {
        id: 1,
        username: 'admin',
        nombre: 'Admin',
        rol: 'admin',
        permisos: ['administracion:usuarios:gestionar'],
        mustChangePassword: false,
      },
    })

    render(
      <MemoryRouter initialEntries={['/secure']}>
        <Routes>
          <Route path="/login" element={<div>Login Page</div>} />
          <Route path="/" element={<div>Root</div>} />
          <Route
            path="/secure"
            element={
              <ProtectedRoute requiredRoles={['admin']}>
                <SecurePage />
              </ProtectedRoute>
            }
          />
        </Routes>
      </MemoryRouter>,
    )

    expect(screen.getByText('Secure Page')).toBeInTheDocument()
  })

  it('F-03-04: requiredRoles no coincide → redirect a /', () => {
    useAuthStore.setState({
      user: { id: 2, username: 'cajero', nombre: 'Cajero', rol: 'cajero', permisos: [], mustChangePassword: false },
    })

    render(
      <MemoryRouter initialEntries={['/secure']}>
        <Routes>
          <Route path="/login" element={<div>Login Page</div>} />
          <Route path="/" element={<div>Root Page</div>} />
          <Route
            path="/secure"
            element={
              <ProtectedRoute requiredRoles={['admin']}>
                <SecurePage />
              </ProtectedRoute>
            }
          />
        </Routes>
      </MemoryRouter>,
    )

    expect(screen.getByText('Root Page')).toBeInTheDocument()
    expect(screen.queryByText('Secure Page')).not.toBeInTheDocument()
  })

  it('F-03-05: requiredPermissions OR — user tiene uno → renderiza children', () => {
    useAuthStore.setState({
      user: {
        id: 2,
        username: 'cajero',
        nombre: 'Cajero',
        rol: 'cajero',
        permisos: ['ventas:contado:crear'],
        mustChangePassword: false,
      },
    })

    render(
      <MemoryRouter initialEntries={['/secure']}>
        <Routes>
          <Route path="/login" element={<div>Login Page</div>} />
          <Route path="/" element={<div>Root Page</div>} />
          <Route
            path="/secure"
            element={
              <ProtectedRoute
                requiredPermissions={['ventas:contado:crear', 'administracion:usuarios:gestionar']}
              >
                <SecurePage />
              </ProtectedRoute>
            }
          />
        </Routes>
      </MemoryRouter>,
    )

    expect(screen.getByText('Secure Page')).toBeInTheDocument()
  })

  it('F-03-06: requiredPermissions — user no tiene ninguno → redirect a /', () => {
    useAuthStore.setState({
      user: {
        id: 2,
        username: 'cajero',
        nombre: 'Cajero',
        rol: 'cajero',
        permisos: ['ventas:contado:crear'],
        mustChangePassword: false,
      },
    })

    render(
      <MemoryRouter initialEntries={['/secure']}>
        <Routes>
          <Route path="/login" element={<div>Login Page</div>} />
          <Route path="/" element={<div>Root Page</div>} />
          <Route
            path="/secure"
            element={
              <ProtectedRoute requiredPermissions={['administracion:usuarios:gestionar']}>
                <SecurePage />
              </ProtectedRoute>
            }
          />
        </Routes>
      </MemoryRouter>,
    )

    expect(screen.getByText('Root Page')).toBeInTheDocument()
    expect(screen.queryByText('Secure Page')).not.toBeInTheDocument()
  })

  it('F-03-07: usuario admin puede acceder a ruta con requiredPermissions', () => {
    useAuthStore.setState({
      user: {
        id: 1,
        username: 'admin',
        nombre: 'Admin',
        rol: 'admin',
        permisos: ['administracion:usuarios:gestionar'],
        mustChangePassword: false,
      },
    })

    render(
      <MemoryRouter initialEntries={['/usuarios/nuevo']}>
        <Routes>
          <Route path="/login" element={<div>Login Page</div>} />
          <Route path="/" element={<div>Root Page</div>} />
          <Route
            path="/usuarios/nuevo"
            element={
              <ProtectedRoute requiredPermissions={['administracion:usuarios:gestionar']}>
                <div>Create User Page</div>
              </ProtectedRoute>
            }
          />
        </Routes>
      </MemoryRouter>,
    )

    expect(screen.getByText('Create User Page')).toBeInTheDocument()
  })

  it('F-03-08: usuario cajero sin permiso no puede acceder a /usuarios/nuevo → redirect a /', () => {
    useAuthStore.setState({
      user: {
        id: 2,
        username: 'cajero',
        nombre: 'Cajero',
        rol: 'cajero',
        permisos: ['ventas:contado:crear'],
        mustChangePassword: false,
      },
    })

    render(
      <MemoryRouter initialEntries={['/usuarios/nuevo']}>
        <Routes>
          <Route path="/login" element={<div>Login Page</div>} />
          <Route path="/" element={<div>Root Page</div>} />
          <Route
            path="/usuarios/nuevo"
            element={
              <ProtectedRoute requiredPermissions={['administracion:usuarios:gestionar']}>
                <div>Create User Page</div>
              </ProtectedRoute>
            }
          />
        </Routes>
      </MemoryRouter>,
    )

    expect(screen.getByText('Root Page')).toBeInTheDocument()
    expect(screen.queryByText('Create User Page')).not.toBeInTheDocument()
  })
})
