# -*- coding: utf-8 -*-
# Copyright 2026 Nexa Systems Inc.
# License OPL-1 (Odoo Proprietary License v1.0)

from odoo import models, fields, api


class FusionProductSyncMapping(models.Model):
    _name = 'fusion.product.sync.mapping'
    _description = 'Product Sync Mapping'
    _rec_name = 'remote_product_name'
    _order = 'remote_product_name'

    config_id = fields.Many2one('fusion.sync.config', string='Sync Config',
                                required=True, ondelete='cascade')
    local_product_id = fields.Many2one('product.template', string='Local Product',
                                       help='The matching product in this Odoo instance')
    auto_matched = fields.Boolean(string='Auto-Matched',
                                  help='True if the product was automatically matched by SKU or name')

    remote_product_id = fields.Integer(string='Remote Product ID', index=True)
    remote_product_name = fields.Char(string='Remote Product Name')
    remote_default_code = fields.Char(string='Remote SKU/Reference')
    remote_barcode = fields.Char(string='Remote Barcode')
    remote_list_price = fields.Float(string='Remote Price')
    remote_category = fields.Char(string='Remote Category')

    remote_qty_available = fields.Float(
        string='Remote On Hand',
        compute='_compute_remote_totals', store=True, readonly=True)
    remote_qty_forecast = fields.Float(
        string='Remote Forecast',
        compute='_compute_remote_totals', store=True, readonly=True)
    last_stock_sync = fields.Datetime(string='Stock Last Updated', readonly=True)

    stock_line_ids = fields.One2many(
        'fusion.sync.stock', 'mapping_id', string='Stock by Warehouse')

    owner_config_id = fields.Many2one(
        'fusion.sync.config', string='Owner Instance',
        help='Which instance owns this inventory in the shared warehouse')

    @api.depends('stock_line_ids.qty_available', 'stock_line_ids.qty_forecast')
    def _compute_remote_totals(self):
        for mapping in self:
            lines = mapping.stock_line_ids
            mapping.remote_qty_available = sum(lines.mapped('qty_available'))
            mapping.remote_qty_forecast = sum(lines.mapped('qty_forecast'))

    _sql_constraints = [
        ('unique_remote_product',
         'UNIQUE(config_id, remote_product_id)',
         'Each remote product can only be mapped once per sync configuration.'),
    ]
