import json

from django.core.management.base import BaseCommand, CommandError

from basic_info import models as basic_models
from basic_info.services import EmployeeUserProvisioningService


class Command(BaseCommand):
    help = "快速创建系统用户并绑定 Employee，适合人工脚本或 MCP 调用。"

    def add_arguments(self, parser):
        parser.add_argument("--username", required=True, help="用户名")
        parser.add_argument("--password", required=True, help="密码")
        parser.add_argument("--display-name", required=True, help="员工显示名称")
        parser.add_argument("--merchant-id", type=int, required=True, help="商户 ID")
        parser.add_argument("--email", default="", help="邮箱（可选）")
        parser.add_argument("--mobile", default="", help="手机号（可选）")
        parser.add_argument("--area", default="", help="地区（可选）")
        parser.add_argument("--description", default="", help="描述（可选）")
        parser.add_argument(
            "--status",
            default=basic_models.EmployeeStatusEnum.ACTIVE,
            help="员工状态枚举文本，默认 在职",
        )
        parser.add_argument("--role-id", type=int, default=None, help="角色 ID（可选）")
        parser.add_argument(
            "--json",
            action="store_true",
            help="以 JSON 输出结果，适合脚本或 MCP 调用",
        )

    def handle(self, *args, **options):
        try:
            result = EmployeeUserProvisioningService.quick_create_employee_user(
                username=options["username"],
                password=options["password"],
                display_name=options["display_name"],
                merchant_id=options["merchant_id"],
                email=options["email"],
                mobile=options["mobile"],
                area=options["area"],
                description=options["description"],
                status=options["status"],
                role_id=options["role_id"],
            )
        except ValueError as exc:
            if options["json"]:
                self.stdout.write(
                    json.dumps(
                        {"ok": False, "error": str(exc)},
                        ensure_ascii=False,
                    )
                )
                return
            raise CommandError(str(exc))

        payload = {
            "ok": True,
            "result": result.to_dict(),
        }
        if options["json"]:
            self.stdout.write(json.dumps(payload, ensure_ascii=False))
            return

        user_payload = payload["result"]["user"]
        employee_payload = payload["result"]["employee"]
        self.stdout.write(self.style.SUCCESS("创建成功"))
        self.stdout.write(
            f"user: id={user_payload['id']} username={user_payload['username']} role_id={user_payload['role_id']}"
        )
        self.stdout.write(
            f"employee: id={employee_payload['id']} name={employee_payload['name']} merchant={employee_payload['merchant']} status={employee_payload['status']}"
        )
