from microdot import Microdot
from models.group import Group
import json

controller = Microdot()
groups = Group()

@controller.get('')
async def list_groups(request):
    """List all groups."""
    return json.dumps(groups), 200, {'Content-Type': 'application/json'}

@controller.get('/<id>')
async def get_group(request, id):
    """Get a specific group by ID."""
    group = groups.read(id)
    if group:
        return json.dumps(group), 200, {'Content-Type': 'application/json'}
    return json.dumps({"error": "Group not found"}), 404

@controller.post('')
async def create_group(request):
    """Create a new group."""
    try:
        data = request.json or {}
        name = data.get("name", "")
        group_id = groups.create(name)
        if data:
            groups.update(group_id, data)
        return json.dumps(groups.read(group_id)), 201, {'Content-Type': 'application/json'}
    except Exception as e:
        return json.dumps({"error": str(e)}), 400

@controller.put('/<id>')
async def update_group(request, id):
    """Update an existing group."""
    try:
        data = request.json
        if groups.update(id, data):
            return json.dumps(groups.read(id)), 200, {'Content-Type': 'application/json'}
        return json.dumps({"error": "Group not found"}), 404
    except Exception as e:
        return json.dumps({"error": str(e)}), 400

@controller.delete('/<id>')
async def delete_group(request, id):
    """Delete a group."""
    if groups.delete(id):
        return json.dumps({"message": "Group deleted successfully"}), 200
    return json.dumps({"error": "Group not found"}), 404
