# -*- coding: utf-8 -*-
"""写入俱乐部服务号配置（H5 网页授权）。不改小程序 wx_appid。"""
from django.core.management.base import BaseCommand, CommandError

from jituan.models import Club


class Command(BaseCommand):
    help = '设置俱乐部 official_appid / official_secret / h5_domain'

    def add_arguments(self, parser):
        parser.add_argument('--club-id', required=True)
        parser.add_argument('--official-appid', required=True)
        parser.add_argument('--official-secret', required=True)
        parser.add_argument('--h5-domain', default='')

    def handle(self, *args, **options):
        club_id = (options['club_id'] or '').strip()
        appid = (options['official_appid'] or '').strip()
        secret = (options['official_secret'] or '').strip()
        h5_domain = (options['h5_domain'] or '').strip()
        if not club_id or not appid or not secret:
            raise CommandError('club-id / official-appid / official-secret 必填')

        try:
            club = Club.query.get(club_id=club_id)
        except Club.DoesNotExist:
            raise CommandError(f'俱乐部不存在: {club_id}')

        club.official_appid = appid
        club.official_secret = secret
        if h5_domain:
            club.h5_domain = h5_domain
        club.save()
        self.stdout.write(self.style.SUCCESS(
            f'已更新 club={club_id} official_appid={appid} '
            f'secret_len={len(secret)} h5_domain={club.h5_domain or "(未改)"}'
        ))
