import uuid
from odoo import models, fields, api


class MarketplaceOrderStage(models.Model):
    _name = 'marketplace.order.stage'
    _description = 'Marketplace Order Stage'
    _order = 'order_id, sequence'

    # Основные поля
    uuid = fields.Char(string='UUID', required=True, default=lambda self: str(uuid.uuid4()), index=True)
    name = fields.Char(string='Stage Name', required=True)
    description = fields.Text(string='Description')
    
    # Связи
    order_id = fields.Many2one('marketplace.order', string='Order', required=True, ondelete='cascade')
    
    # Тип этапа
    stage_type = fields.Selection([
        ('transport', 'Transport'),
        ('service', 'Service')
    ], string='Stage Type', required=True, default='transport')
    
    # Тип транспорта (только для transport)
    transport_type = fields.Selection([
        ('auto', 'Auto Transport'),
        ('rail', 'Rail Transport'),
        ('sea', 'Sea Transport'),
        ('air', 'Air Transport')
    ], string='Transport Type')
    
    # Локации
    source_location_id = fields.Many2one(
        'logistics.node', 
        string='Source Location',
        help='Start location for transport stages'
    )
    destination_location_id = fields.Many2one(
        'logistics.node', 
        string='Destination Location',
        help='End location for transport stages'
    )
    location_id = fields.Many2one(
        'logistics.node', 
        string='Service Location',
        help='Single location for service stages'
    )
    
    # Порядок
    sequence = fields.Integer(string='Sequence', default=10)
    
    # Перевозчик для service этапов
    selected_carrier_id = fields.Many2one(
        'carrier',
        string='Selected Carrier',
        help='Carrier selected for service stages'
    )
    
    # Связанные записи
    trip_ids = fields.One2many('marketplace.order.trip', 'stage_id', string='Trips')
    
    # Дополнительная информация
    notes = fields.Text(string='Notes')
    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)
    
    
    @api.onchange('stage_type')
    def _onchange_stage_type(self):
        if self.stage_type == 'service':
            self.transport_type = False
            self.source_location_id = False
            self.destination_location_id = False
        else:
            self.location_id = False
            self.selected_carrier_id = False
    
    @api.constrains('stage_type', 'transport_type', 'source_location_id', 'destination_location_id', 'location_id')
    def _check_locations(self):
        for stage in self:
            if stage.stage_type == 'transport':
                if not stage.transport_type:
                    raise ValueError('Transport type is required for transport stages')
                if not stage.source_location_id or not stage.destination_location_id:
                    raise ValueError('Source and destination locations are required for transport stages')
            elif stage.stage_type == 'service':
                if not stage.location_id:
                    raise ValueError('Service location is required for service stages')
    
    def write(self, vals):
        vals['updated_at'] = fields.Datetime.now()
        return super().write(vals)