import logging

_logger = logging.getLogger(__name__)


class CredentialService:

    def create_accounts(self, env, valid_rows, entity_id):
        """Create res.users records from validated CSV rows.

        Each user gets password=national_id, account_source='entity_bulk_upload',
        and account_status='activated'.

        Args:
            env: Odoo environment.
            valid_rows: list of dicts with keys name, email, national_id, phone.
            entity_id: int, the entity that owns these students.

        Returns:
            recordset of created res.users.
        """
        User = env['res.users']
        created_users = User
        for row in valid_rows:
            try:
                user = User.sudo().create({
                    'name': row['name'],
                    'login': row['email'],
                    'email': row['email'],
                    'phone': row.get('phone', ''),
                    'password': row['national_id'],
                    'account_source': 'entity_bulk_upload',
                    'account_status': 'activated',
                    'entity_id': entity_id,
                })
                created_users |= user
            except Exception:
                _logger.exception("Failed to create account for %s", row.get('email'))
        return created_users

    def send_credentials(self, env, user_ids):
        """Send credential emails to newly created users.

        Args:
            env: Odoo environment.
            user_ids: list of int, res.users IDs.
        """
        Mail = env['mail.mail']
        for user in env['res.users'].sudo().browse(user_ids):
            mail_values = {
                'subject': 'Your EnCoach Account Credentials',
                'email_from': env.company.email or 'noreply@encoach.com',
                'email_to': user.email,
                'body_html': (
                    f'<p>Dear {user.name},</p>'
                    f'<p>Your EnCoach account has been created.</p>'
                    f'<p>Login: {user.login}</p>'
                    f'<p>Password: Your National ID</p>'
                    f'<p>Please change your password after first login.</p>'
                ),
            }
            mail = Mail.sudo().create(mail_values)
            mail.send()

    def resend_credentials(self, env, user_id):
        """Resend credential email for a single user.

        Args:
            env: Odoo environment.
            user_id: int, res.users ID.
        """
        self.send_credentials(env, [user_id])
