#!/usr/bin/env python
"""
@Project ：django_base_ai
@File    ：core_base_auth.py
@Author  ：congxing.wang
@Date    ：2025/02/09
@Desc    ：权限相关 JSON 扩展字段
"""

import json

from django.db import models

from django_base_ai.utils import format_core_base_auth


class CoreBaseAuthField(models.JSONField):
    def __init__(self, *args, db_collation=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.db_collation = db_collation
        self.args = args
        self.kwargs = kwargs

    def get_db_prep_value(self, value, connection, prepared=False):
        if prepared:
            return connection.ops.adapt_json(value, self.encoder)
        return json.dumps(format_core_base_auth.create_update_auth_json(value))

    def from_db_value(self, value, expression, connection):
        if value:
            from django_base_ai.system.models import CoreBaseAuth

            nid = json.loads(value).get("nid", 0)
            django_base_ai_auth = CoreBaseAuth.objects.filter(id=nid).first()
            value = format_core_base_auth.get_auth_json(
                django_base_ai_auth.target_data if django_base_ai_auth else [], nid
            )
        return value
