"""
Make sure every tenant has an enabled row for each always-on module.

has_module() already returns True for always-on modules regardless of the
stored rows, so this is about keeping the database honest rather than fixing
behaviour. It matters for the modules page and the Fleet check-in, which read
the rows directly.

    python manage.py enable_always_on_modules
    python manage.py enable_always_on_modules --dry-run
"""
from django.core.management.base import BaseCommand

from apps.tenants.models import (
    ALWAYS_ON_MODULES, MODULE_CHOICES, Tenant, TenantModule,
)


class Command(BaseCommand):
    help = 'Enable every always-on module row for every tenant.'

    def add_arguments(self, parser):
        parser.add_argument('--dry-run', action='store_true')

    def handle(self, *args, **options):
        dry_run = options['dry_run']
        labels = dict(MODULE_CHOICES)
        changed = 0

        for tenant in Tenant.objects.all().order_by('name'):
            for key in sorted(ALWAYS_ON_MODULES):
                row = TenantModule.objects.filter(tenant=tenant, module=key).first()
                if row and row.is_enabled:
                    continue

                label = labels.get(key, key)
                if dry_run:
                    state = 'missing' if row is None else 'disabled'
                    self.stdout.write(f'  {tenant.name}: {label} is {state}, would enable.')
                else:
                    TenantModule.objects.update_or_create(
                        tenant=tenant, module=key, defaults={'is_enabled': True},
                    )
                    self.stdout.write(f'  {tenant.name}: enabled {label}.')
                changed += 1

        if not changed:
            self.stdout.write('Nothing to do. Every tenant already has all always-on modules.')
            return

        verb = 'Would enable' if dry_run else 'Enabled'
        self.stdout.write(self.style.SUCCESS(f'{verb} {changed} module row(s).'))
