import uuid
import logging

from odoo import models, fields, api, _

_logger = logging.getLogger(__name__)


class Carrier(models.Model):
    _name = 'carrier'
    _description = 'Carrier'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _order = 'create_date desc'

    name = fields.Char(
        'Reference',
        required=True,
        copy=False,
        readonly=True,
        default=lambda self: _('New'),
    )
    uuid = fields.Char(
        'UUID',
        required=True,
        readonly=True,
        default=lambda self: str(uuid.uuid4()),
        index=True,
    )
    team_uuid = fields.Char(
        'Team UUID',
        required=True,
        index=True,
        tracking=True,
    )
    team_name = fields.Char(
        'Team Name',
        required=True,
        tracking=True,
    )
    logto_org_id = fields.Char(
        'Logto Organization ID',
        readonly=True,
        index=True,
        tracking=True,
    )

    # Company data
    tax_id = fields.Char('Tax ID', tracking=True)
    registration_number = fields.Char('Registration Number', tracking=True)
    country_id = fields.Many2one('res.country', 'Country', tracking=True)

    # Contact
    contact_person = fields.Char('Contact Person')
    contact_email = fields.Char('Contact Email')
    contact_phone = fields.Char('Contact Phone')

    # Status
    state = fields.Selection([
        ('pending', 'Pending'),
        ('active', 'Active'),
        ('suspended', 'Suspended'),
    ], string='Status', default='pending', required=True, tracking=True)

    is_active = fields.Boolean('Active', default=True)
    joined_date = fields.Date(
        'Joined Date',
        default=fields.Date.today,
        tracking=True,
    )

    _sql_constraints = [
        ('unique_uuid', 'UNIQUE(uuid)', 'UUID must be unique!'),
        ('unique_team_uuid', 'UNIQUE(team_uuid)', 'Team UUID must be unique!'),
    ]

    @api.model
    def create(self, vals):
        if vals.get('name', _('New')) == _('New'):
            vals['name'] = self.env['ir.sequence'].next_by_code('carrier') or _('New')
        return super().create(vals)

    def name_get(self):
        result = []
        for carrier in self:
            name = f"{carrier.name} - {carrier.team_name}"
            result.append((carrier.id, name))
        return result
