import json
import logging

from odoo import http
from odoo.http import request
from odoo.addons.encoach_api.controllers.base import (
    jwt_required, _json_response, _error_response,
)

_logger = logging.getLogger(__name__)


class EntityController(http.Controller):

    @http.route('/api/entities', type='http', auth='none',
                methods=['GET'], csrf=False)
    @jwt_required
    def list_entities(self, **kw):
        try:
            cr = request.env.cr
            cr.execute(
                "SELECT id, name, code, type FROM encoach_entity ORDER BY name")
            items = []
            for eid, name, code, etype in cr.fetchall():
                items.append({
                    'id': eid,
                    'name': name,
                    'code': code or '',
                    'type': etype or '',
                })
            return _json_response({'items': items, 'total': len(items)})
        except Exception as e:
            _logger.exception('list entities failed')
            return _json_response({'error': str(e)}, 500)
