from datetime import timedelta

from odoo import _, api, fields, models
from odoo.exceptions import UserError


class MailQuickTemplateLog(models.Model):
    _name = 'mail.quick.template.log'
    _description = 'Chatter Quick Reply Template Usage Log'
    _order = 'used_date desc, id desc'
    # Append-only system log: do not track create_uid/write_uid/etc.
    _log_access = False

    template_id = fields.Many2one(
        'mail.quick.template', string='Template', ondelete='set null',
        index=True,
        help="Preserved as NULL if the template is later deleted.",
    )
    template_name = fields.Char(
        string='Template Name', required=True,
        help="Copy of the template name at the time of use (kept even if the "
             "template is deleted).",
    )
    user_id = fields.Many2one(
        'res.users', string='Used By', ondelete='set null', index=True,
        help="Set to empty if the user is later deleted; the log row is kept.",
    )
    used_date = fields.Datetime(
        string='Used On', required=True, default=fields.Datetime.now,
        index=True,
    )
    res_model = fields.Char(string='Record Model', required=True)
    res_id = fields.Integer(string='Record ID', required=True)
    company_id = fields.Many2one(
        'res.company', string='Company', required=True,
        default=lambda self: self.env.company, index=True,
    )

    # Composite indexes for fast per-user / per-company analytics (Section 4.4).
    _user_date_idx = models.Index('(user_id, used_date)')
    _company_date_idx = models.Index('(company_id, used_date)')

    def write(self, vals):
        """BR-18: the usage log is append-only. No updates permitted."""
        raise UserError(_("Usage log records cannot be modified."))

    def unlink(self):
        """The log is append-only. Deletion is only allowed via the optional
        retention cron (which runs as superuser)."""
        if not self.env.su:
            raise UserError(_("Usage log records cannot be deleted."))
        return super().unlink()

    @api.model
    def _cron_purge_old_logs(self):
        """Optional retention purge (disabled by default, Section 10.1)."""
        retention_days = int(self.env['ir.config_parameter'].sudo().get_param(
            'do_mail_quick_templates.log_retention_days', default=365
        ))
        cutoff = fields.Datetime.now() - timedelta(days=retention_days)
        self.sudo().search([('used_date', '<', cutoff)]).unlink()
