# Task Team Connector — OAuth2 authorization codes
import secrets
from datetime import datetime, timedelta

from odoo import api, fields, models


class TaskTeamOAuthCode(models.Model):
    _name = 'task.team.oauth.code'
    _description = 'Task Team OAuth2 Authorization Code'

    code = fields.Char(string='Code', required=True, index=True, readonly=True)
    user_id = fields.Many2one('res.users', string='User', required=True, ondelete='cascade')
    client_id = fields.Char(string='Client ID', required=True)
    redirect_uri = fields.Char(string='Redirect URI')
    state = fields.Char(string='State')
    expires_at = fields.Datetime(string='Expires At', required=True)
    used = fields.Boolean(string='Consumed', default=False)

    @api.model
    def generate_code(self, user_id, client_id, redirect_uri='', state=''):
        """Issue a new single-use authorization code valid for 10 minutes."""
        code = secrets.token_urlsafe(32)
        self.create({
            'code': code,
            'user_id': user_id,
            'client_id': client_id,
            'redirect_uri': redirect_uri or '',
            'state': state or '',
            'expires_at': datetime.utcnow() + timedelta(minutes=10),
        })
        return code

    @api.model
    def validate_and_consume(self, code, client_id):
        """Validate code, mark it as used, and return the record (or None)."""
        record = self.search(
            [
                ('code', '=', code),
                ('client_id', '=', client_id),
                ('used', '=', False),
                ('expires_at', '>', datetime.utcnow()),
            ],
            limit=1,
        )
        if not record:
            return None
        record.write({'used': True})
        return record

    @api.model
    def cleanup_expired(self):
        """Cron: remove expired / used codes."""
        self.search(
            ['|', ('expires_at', '<', datetime.utcnow()), ('used', '=', True)]
        ).unlink()
