from rest_framework import status

from api.models import EsTag
from api.models.audit_trail import AuditTrail
from api.models.audit_trail_details import AuditTrailDetails
from api.views.admin.base import AdminApiBase
from api.validator import BaseValidator
from api.utils import log_critical_error, get_exception_detail, get_ip, get_multiple_old_new_data
from rest_framework.exceptions import ValidationError
from api.translation import __


class TagUpdate(AdminApiBase):
    def validate_request(self,request):
        rules = {
            "id": "required|array|exists:api.EsTag,id",
        }
        # if need rename field, can put here
        attribute = {
            # "email": __("attr.email"),
        }
        # validate id first, cause need get tag by id, if wrong id direct return error
        validator = BaseValidator(request.data,rules,attribute)
        error = validator.validate()
        if error:
            raise ValidationError(error)

        edit_tag = (
            EsTag.objects
            # .select_related("tag") # need get current parent also, incase got update can get the old parent
            # .prefetch_related(
            #     "sub_tag",
            #     "tag__tag" # tags means the relation add in models, __tag means the relation table tag_id get the tag object #2
            # )
            .filter(id__in=request.data.get("id"))
        )

        rules = {
            "name": "nullable",
            "desc": "nullable",
        }

        if request.data.get("code") and edit_tag.count() == 1:
            tag = edit_tag.first()
            if request.data.get("code") != tag.code:
                rules['code'] = "nullable|not_exists:api.EsTag,code"

        # if need rename field, can put here
        attribute = {
            # "email": __("attr.email"),
        }

        validator = BaseValidator(request.data,rules,attribute)
        error = validator.validate()

        # custom error after basic validation

        if error:
            raise ValidationError(error)

        return edit_tag


    def post(self, request):
        # Validate input
        try:
            edit_tag = self.validate_request(request)

            action="tag_update" # this is for audit log only

            updated = False
            update_fields = {}
            ignore_fields = ['id','timestamp','signature']
            # if more than 1 tag edit, ignore code
            if edit_tag.count() > 1 or not request.data.get("code"):
                ignore_fields.append('code')
            valid_fields = {f.column for f in EsTag._meta.fields}
            for key, val in request.data.items():
                if key not in ignore_fields and key in valid_fields:
                    updated = True
                    match key:
                        case _:
                            # default the key will same as db column name
                            update_fields[key] = val

            # be4 save need get the old new data already, because bulk update is no matter got change or no changes also will update
            old_new_data = get_multiple_old_new_data(edit_tag,request.data.items(),ignore_fields,valid_fields)
            if updated and update_fields:
                update_fields['updated_by'] = request.user.id
                edit_tag.update(**update_fields)

            if old_new_data['old_data'] or old_new_data['new_data']:
                # insert audit trail and details
                # can insert the parent first, then only insert details
                audit_trail = AuditTrail.objects.create(
                    user_id=request.user.id,
                    type=self.audit_type,
                    ip_address=get_ip(request)
                )

                code = ",".join(edit_tag.values_list("code", flat=True))
                remark_param = {
                    "code":code
                }

                # call to a function for insert details, so in future if want change to used worker, can modify in function only
                AuditTrailDetails.custom_insert(
                    audit_trail=audit_trail,
                    action=action,
                    remark_param=remark_param,
                    new_data=old_new_data['new_data'],
                    old_data=old_new_data['old_data'],
                )

            response = {

            }

            return self.api_response(data=response)
        except ValidationError as e:
            first_message = e.detail['error']
            errors = e.detail['errors']
            return self.api_response(error=first_message,errors=errors,code=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            e_details = get_exception_detail(e)
            log_critical_error(user_id=None,descr=e_details['descr'],url=e_details['url'],trace=e_details['trace'])
            return self.api_response(error=__("message.internal_server_error"),code=status.HTTP_500_INTERNAL_SERVER_ERROR)