from odoo import api, fields, models


class WooSyncLog(models.Model):
    _name = 'woo.sync.log'
    _description = 'WooCommerce Sync Log'
    _order = 'create_date desc'

    instance_id = fields.Many2one('woo.instance', ondelete='cascade')
    sync_type = fields.Selection([
        ('product', 'Product'),
        ('order', 'Order'),
        ('invoice', 'Invoice'),
        ('inventory', 'Inventory'),
        ('customer', 'Customer'),
    ])
    direction = fields.Selection([
        ('odoo_to_woo', 'Odoo \u2192 WooCommerce'),
        ('woo_to_odoo', 'WooCommerce \u2192 Odoo'),
    ])
    record_ref = fields.Char()
    state = fields.Selection([
        ('success', 'Success'),
        ('failed', 'Failed'),
        ('conflict', 'Conflict'),
    ])
    message = fields.Text()
    company_id = fields.Many2one(
        'res.company', default=lambda self: self.env.company,
    )

    @api.model
    def _cron_cleanup_logs(self):
        """Purge sync logs older than 90 days (180 for errors)."""
        cutoff_success = fields.Datetime.subtract(fields.Datetime.now(), hours=90 * 24)
        cutoff_error = fields.Datetime.subtract(fields.Datetime.now(), hours=180 * 24)
        self.search([
            '|',
            '&', ('state', '!=', 'failed'), ('create_date', '<', cutoff_success),
            '&', ('state', '=', 'failed'), ('create_date', '<', cutoff_error),
        ]).unlink()
