import { extractPythonRoutes } from '../../../model/route-discovery/python'

describe('Python Route Extractor', () => {
  describe('Flask routes', () => {
    it('extracts @app.route with default GET', () => {
      const content = `
from flask import Flask
app = Flask(__name__)

@app.route('/api/users')
def get_users():
    return jsonify(users)
`
      const routes = extractPythonRoutes(content, 'app.py')
      expect(routes).toHaveLength(1)
      expect(routes[0].methods).toEqual(['GET'])
      expect(routes[0].path).toBe('/api/users')
      expect(routes[0].framework).toBe('flask')
      expect(routes[0].handler).toBe('get_users')
    })

    it('extracts @app.route with explicit methods', () => {
      const content = `
@app.route('/api/items', methods=['GET', 'POST'])
def items():
    pass
`
      const routes = extractPythonRoutes(content, 'views.py')
      expect(routes).toHaveLength(1)
      expect(routes[0].methods).toEqual(['GET', 'POST'])
    })

    it('detects @login_required decorator', () => {
      const content = `
@app.route('/api/profile')
@login_required
def profile():
    pass
`
      const routes = extractPythonRoutes(content, 'views.py')
      expect(routes).toHaveLength(1)
      expect(routes[0].authMiddleware).toContain('@login_required')
    })

    it('converts Flask path params to :param format', () => {
      const content = `
@app.route('/api/users/<int:user_id>')
def get_user(user_id):
    pass
`
      const routes = extractPythonRoutes(content, 'views.py')
      expect(routes).toHaveLength(1)
      expect(routes[0].path).toBe('/api/users/:user_id')
    })

    it('detects Flask input sources', () => {
      const content = `
@app.route('/api/search', methods=['POST'])
def search():
    data = request.json
    q = request.args.get('q')
    return jsonify(results=[])
`
      const routes = extractPythonRoutes(content, 'views.py')
      expect(routes).toHaveLength(1)
      const sources = routes[0].inputs.map(i => i.source)
      expect(sources).toContain('body')
      expect(sources).toContain('query')
    })
  })

  describe('Django routes', () => {
    it('extracts Django path() in urlpatterns', () => {
      const content = `
from django.urls import path
from . import views

urlpatterns = [
    path('api/search/', views.search_view, name='search'),
    path('api/users/<int:pk>/', views.UserDetailView.as_view(), name='user-detail'),
]
`
      const routes = extractPythonRoutes(content, 'urls.py')
      expect(routes).toHaveLength(2)
      expect(routes[0].path).toBe('/api/search/')
      expect(routes[0].framework).toBe('django')
      expect(routes[1].path).toBe('/api/users/:pk/')
    })
  })

  it('skips non-Python files', () => {
    const routes = extractPythonRoutes('app.get("/test", handler)', 'server.js')
    expect(routes).toHaveLength(0)
  })
})
