from odoo import models, fields, api
import logging
from datetime import timedelta

_logger = logging.getLogger(__name__)

class ShopifyStockQueue(models.Model):
    _name = 'shopify.stock.queue'
    _description = 'Shopify Stock Sync Queue'
    
    product_id = fields.Many2one('product.product', string='Product', required=True, ondelete='cascade')
    state = fields.Selection([
        ('pending', 'Pendiente'),
        ('done', 'Realizado'),
        ('failed', 'Fallido')
    ], string='Estado', default='pending', required=True)
    error_message = fields.Text(string='Mensaje de Error')
    
    @api.model
    def enqueue_product(self, product_id):
        existing = self.search([
            ('product_id', '=', product_id),
            ('state', 'in', ['pending', 'failed'])
        ], limit=1)
        if not existing:
            self.create({'product_id': product_id, 'state': 'pending'})
            
    @api.model
    def process_queue_batch(self):
        records = self.search([('state', 'in', ['pending', 'failed'])], limit=15)
        if not records:
            return
            
        config = self.env['shopify.config'].sudo().search([('state', '=', 'confirmed')], limit=1)
        if not config or not config.auto_sync_products:
            return

        products = records.mapped('product_id').filtered(lambda p: p.shopify_inventory_item_id)
        if products:
            try:
                config._sync_variants_stock_to_shopify(products)
                records.write({'state': 'done', 'error_message': False})
            except Exception as e:
                _logger.error("[Shopify Stock Queue] Falló sincronización de lote: %s", str(e))
                records.write({'state': 'failed', 'error_message': str(e)})
        else:
            records.write({'state': 'done', 'error_message': 'No Shopify Inventory Item ID'})

    @api.model
    def clean_done_queue(self):
        threshold_date = fields.Datetime.now() - timedelta(days=7)
        old_records = self.search([('state', '=', 'done'), ('create_date', '<', threshold_date)])
        if old_records:
            old_records.unlink()
