# Task Team Connector — User mapping
import logging

from odoo import fields, models

_logger = logging.getLogger(__name__)


class ResUsers(models.Model):
    _inherit = 'res.users'

    tt_user_id = fields.Char(
        string='Task Team User ID',
        readonly=True,
        copy=False,
        help='UUID of this Odoo user in the Task Team database',
    )

    def _tt_get_or_create_user(self):
        """Return the Task Team UUID for this user, creating the account if needed."""
        self.ensure_one()
        if self.tt_user_id:
            return self.tt_user_id

        from ..services.api_client import TaskTeamApiClient
        ICP = self.env['ir.config_parameter'].sudo()
        api_url = ICP.get_param('task_team_connector.api_url', 'https://api.hasdo.info/api/v1')
        api_key = ICP.get_param('task_team_connector.api_key', '')

        try:
            client = TaskTeamApiClient(api_url, api_key)
            result = client.get_or_create_user(email=self.email, name=self.name)
            tt_id = (result or {}).get('data', {}).get('id')
            if tt_id:
                self.sudo().write({'tt_user_id': tt_id})
                return tt_id
        except Exception as exc:
            _logger.error('Failed to resolve Task Team user for %s: %s', self.email, exc)
        return None
