import uuid
from odoo import models, fields, api


class MarketplaceOrder(models.Model):
    _name = 'marketplace.order'
    _description = 'Marketplace Order'
    _order = 'created_at desc'

    # Основные поля
    uuid = fields.Char(string='UUID', required=True, default=lambda self: str(uuid.uuid4()), index=True)
    name = fields.Char(string='Order Number', required=True, default='New')
    
    # Связи
    team_uuid = fields.Char(string='Team UUID', required=True, index=True)
    user_id = fields.Char(string='User ID', required=True)  # Logto user ID
    
    # Логистика
    source_location_id = fields.Many2one(
        'logistics.node', 
        string='Source Location', 
        required=True,
        help='Logistics node where goods are picked up'
    )
    destination_location_id = fields.Many2one(
        'logistics.node', 
        string='Destination Location', 
        required=True,
        help='Logistics node where goods are delivered'
    )
    
    # Суммы
    
    total_amount = fields.Float(string='Total Amount', compute='_compute_total_amount', store=True)
    currency_id = fields.Many2one('res.currency', string='Currency', default=lambda self: self.env.company.currency_id)
    
    # Даты
    created_at = fields.Datetime(string='Created At', default=fields.Datetime.now, required=True)
    updated_at = fields.Datetime(string='Updated At', default=fields.Datetime.now, required=True)
    
    # Связанные записи
    order_lines = fields.One2many('marketplace.order.line', 'order_id', string='Order Lines')
    tracking_events = fields.One2many('marketplace.order.tracking', 'order_id', string='Tracking Events')
    stage_ids = fields.One2many('marketplace.order.stage', 'order_id', string='Stages')
    
    # Дополнительная информация
    notes = fields.Text(string='Notes')
    
    @api.depends('order_lines.subtotal')
    def _compute_total_amount(self):
        for order in self:
            order.total_amount = sum(line.subtotal for line in order.order_lines)
    
    @api.model
    def create(self, vals):
        if vals.get('name', 'New') == 'New':
            vals['name'] = self.env['ir.sequence'].next_by_code('marketplace.order') or 'New'
        return super().create(vals)
    
    def write(self, vals):
        vals['updated_at'] = fields.Datetime.now()
        return super().write(vals)
    
