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

import logging

_logger = logging.getLogger(__name__)

class ResUsers(models.Model):
    _inherit = 'res.users'

    def unlink(self):
        for user in self:
            grants = self.env['grant.benefit'].search([
                ('user_id', '=', user.id),
                ('state', 'not in', ['draft', 'new'])
            ])
            if grants:
                grant_info = ', '.join('[%s: %s]' % (g.code or g.name or g.id, dict(self.env['grant.benefit']._fields['state'].selection).get(g.state)) for g in grants)
                raise ValidationError(
                    _("Cannot delete user '%s': linked to Benefits - Profiles %s") % (user.name, grant_info)
                )
        partners = self.mapped('partner_id')

        for user in self:
            benefits = self.env['grant.benefit'].search([('user_id', '=', user.id)])
            benefits.with_context(skip_user_unlink=True).unlink()

        res = super(ResUsers, self).unlink()

        for partner in partners:
            still_linked = self.env['res.users'].search([('partner_id', '=', partner.id)], limit=1)
            if not still_linked:
                try:
                    partner.unlink()
                except Exception as e:
                    _logger.warning(
                        "Failed to delete partner ID %s after user removal. Reason: %s", partner.id, str(e)
                    )
                    raise ValidationError(
                        _("Failed to delete partner '%s' (ID: %s) after user removal. Reason: %s")
                        % (partner.display_name, partner.id, str(e))
                    )

        return res
