from django.utils import timezone
from rest_framework import status
from rest_framework.exceptions import ValidationError

from api.models import EsPos
from api.models.audit_trail import AuditTrail
from api.models.audit_trail_details import AuditTrailDetails
from api.translation import __
from api.utils import log_critical_error, get_exception_detail, get_ip
from api.validator import BaseValidator
from api.views.admin.base import AdminApiBase


class PosUpdate(AdminApiBase):
    def validate_request(self, request):
        rules = {
            "id": "required|array|exists:api.EsPos,id",
        }

        attribute = {}
        # validate id first
        validator = BaseValidator(request.data, rules, attribute)
        error = validator.validate()
        if error:
            raise ValidationError(error)

        edit_obj = (
            EsPos.objects
            .filter(id__in=request.data.get("id"))
        )
        obj = edit_obj.first()

        status_code_string = ",".join(str(v) for v in EsPos.STATUS_TO_CODE.values())
        rules = {
            "name": "nullable",
            "desc": "nullable",
            "status": "nullable|in:" + status_code_string,
            "department_id": "nullable|exists:api.EsDepartment,id",
            "extra_data_1": "nullable",
            "extra_data_2": "nullable",
            "extra_data_3": "nullable",
            "extra_data_4": "nullable",
            "extra_data_5": "nullable",
            "extra_data_6": "nullable",
            "extra_data_7": "nullable",
            "extra_data_8": "nullable",
            "extra_data_9": "nullable",
            "extra_data_10": "nullable",
        }

        if request.data.get("code") and edit_obj.count() == 1 and request.data.get("code") != obj.code:
            rules['code'] = "nullable|not_exists:api.EsPos,code"

        validator = BaseValidator(request.data, rules, attribute)
        error = validator.validate()
        if error:
            raise ValidationError(error)

        return edit_obj

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

            action = "pos_update"  # this is for audit log only
            old_new_data = {
                "new_data": {},
                "old_data": {},
            }
            updated = False
            update_fields = {}
            # if more than 1 role edit, ignore code
            if edit_obj.count() == 1:
                current_edit_obj = edit_obj.first()
                if "code" in request.data:
                    old_new_data.setdefault("old_data", {}).setdefault(current_edit_obj.id, {})["code"] = current_edit_obj.code
                    old_new_data.setdefault("new_data", {}).setdefault(current_edit_obj.id, {})["code"] = request.data.get("code")
                    update_fields['code'] = request.data['code']
                    updated = True

            ignore_fields = ['id', 'timestamp', 'signature']
            valid_fields = {f.column for f in EsPos._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

            if updated and update_fields:
                for obj in edit_obj:
                    for key, val in update_fields.items():
                        old_val = getattr(obj, key)
                        # Only track if it truly changed
                        if str(old_val) != str(val):
                            old_new_data.setdefault("old_data", {}).setdefault(obj.id, {})[key] = str(old_val) if old_val is not None else None
                            old_new_data.setdefault("new_data", {}).setdefault(obj.id, {})[key] = val

                update_fields['updated_by'] = request.user.id
                update_fields['updated_at'] = timezone.now()
                edit_obj.update(**update_fields)

            if old_new_data['old_data'] or old_new_data['new_data']:
                audit_trail = AuditTrail.objects.create(
                    user_id=request.user.id,
                    type=self.audit_type,
                    ip_address=get_ip(request)
                )

                names = ",".join(edit_obj.values_list("name", flat=True))
                remark_param = {
                    "name": names
                }

                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=request.user.id, 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)
