from odoo.exceptions import UserError
from odoo.tests.common import tagged

from .common import QuickTemplateCommon


@tagged('post_install', '-at_install')
class TestMailQuickTemplateLog(QuickTemplateCommon):

    def _make_log(self, tmpl):
        return self.Log.create({
            'template_id': tmpl.id,
            'template_name': tmpl.name,
            'user_id': self.env.user.id,
            'res_model': 'res.partner',
            'res_id': 1,
            'company_id': self.company.id,
        })

    def test_log_append_only_no_write(self):
        tmpl = self._make_template(name='Log')
        log = self._make_log(tmpl)
        with self.assertRaises(UserError):
            log.write({'res_id': 2})

    def test_log_no_unlink_for_user(self):
        tmpl = self._make_template(name='Log2')
        log = self._make_log(tmpl)
        with self.assertRaises(UserError):
            log.with_user(self.manager).unlink()

    def test_log_survives_template_delete(self):
        tmpl = self._make_template(name='LogDel')
        log = self._make_log(tmpl)
        tmpl.unlink()  # admin, use_count 0
        self.assertTrue(log.exists())
        self.assertFalse(log.template_id)
        self.assertEqual(log.template_name, 'LogDel')

    def test_purge_cron(self):
        from odoo import fields
        from datetime import timedelta
        tmpl = self._make_template(name='Purge')
        log = self._make_log(tmpl)
        log_old = self._make_log(tmpl)
        # Force one log far in the past.
        self.env.cr.execute(
            "UPDATE mail_quick_template_log SET used_date = %s WHERE id = %s",
            (fields.Datetime.now() - timedelta(days=800), log_old.id),
        )
        self.env['ir.config_parameter'].sudo().set_param(
            'do_mail_quick_templates.log_retention_days', '365'
        )
        self.Log._cron_purge_old_logs()
        self.assertFalse(log_old.exists())
        self.assertTrue(log.exists())
