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


class MailQuickTemplateCategory(models.Model):
    _name = 'mail.quick.template.category'
    _description = 'Chatter Quick Reply Template Category'
    _inherit = ['mail.thread']
    _order = 'sequence, name, id'

    name = fields.Char(
        string='Category Name', required=True, translate=True, tracking=True,
        index='trigram',
    )
    sequence = fields.Integer(string='Sequence', default=10)
    company_id = fields.Many2one(
        'res.company', string='Company', required=True,
        default=lambda self: self.env.company, index=True,
    )
    active = fields.Boolean(string='Active', default=True, tracking=True)
    template_count = fields.Integer(
        string='Templates', compute='_compute_template_count', store=False,
    )
    color = fields.Integer(string='Color Index', default=0)

    template_ids = fields.One2many(
        'mail.quick.template', 'category_id', string='Category Templates',
    )

    _name_company_uniq = models.Constraint(
        'UNIQUE(name, company_id)',
        'Category name must be unique per company.',
    )
    # Composite index for ordered per-company fetches (Section 4.1).
    _company_sequence_idx = models.Index('(company_id, sequence)')

    @api.model_create_multi
    def create(self, vals_list):
        """Suppress the chatter "record created" log (Section 18: avoid chatter
        spam) and the core reply-to/company computation that can raise an
        AccessError for restricted Template Managers when accounting is
        installed. Field tracking on later edits is unaffected."""
        return super(
            MailQuickTemplateCategory,
            self.with_context(mail_create_nolog=True),
        ).create(vals_list)

    @api.depends('template_ids', 'template_ids.active')
    def _compute_template_count(self):
        """Count active templates only (Section 4.1)."""
        Template = self.env['mail.quick.template']
        for rec in self:
            if rec.id:
                rec.template_count = Template.search_count(
                    [('category_id', '=', rec.id)]
                )
            else:
                rec.template_count = 0

    @api.constrains('name')
    def _check_name_not_empty(self):
        for rec in self:
            if not rec.name or not rec.name.strip():
                raise ValidationError(
                    _("Category name cannot be empty or whitespace.")
                )

    def unlink(self):
        """BR-12: A category can only be deleted if it has zero associated
        templates (active OR archived)."""
        Template = self.env['mail.quick.template'].with_context(active_test=False)
        for rec in self:
            if Template.search_count([('category_id', '=', rec.id)]):
                raise ValidationError(_(
                    "Cannot delete a category that contains templates. "
                    "Please reassign or delete the templates first."
                ))
        return super().unlink()

    def action_open_templates(self):
        """Smart button: show the templates of this category."""
        self.ensure_one()
        return {
            'type': 'ir.actions.act_window',
            'name': _('Templates'),
            'res_model': 'mail.quick.template',
            'view_mode': 'list,form,kanban',
            'domain': [('category_id', '=', self.id)],
            'context': {'default_category_id': self.id},
        }
