from rest_framework import serializers, status
from api.models import TtUsagePreference, TtTravelTable, TtSetting, TtZone, TtJourney
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 decrypt_aes_128_cbc, encrypt_aes_128_cbc, generate_kafka_data, log_critical_error, \
    get_exception_detail, \
    get_add_new_data, get_ip, bulk_sync_to_redis, get_next_available_code, get_start_and_end_slot
from rest_framework.exceptions import ValidationError
from api.translation import __
from backend.kafka import send_request
from backend.redis_client import redis_client


class TravelTableCreate(AdminApiBase):
    def validate_request(self,request):
        status_code_string = ",".join(str(v) for v in TtTravelTable.STATUS_TO_CODE.values())

        # FE will request by pattern, so can reduce the changes from FE, and BE will convert this pattern become start_slot and end_slot
        rules = {
            "code": "nullable|not_exists:api.TtTravelTable,code",
            "name": "required",
            "desc": "nullable",
            "department_id": "nullable|exists:api.TtDepartment,id",
            "journeys": "nullable|array",
            "tag": "nullable|array|exists:api.TtTag,id",
        }

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

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

        """
        [
            {
                "from_zone": 1,
                "to_zone": 2,
                "slot_required: 1,
            },
            {
                "from_zone": 4,
                "to_zone": 1,
                "slot_required: 1,
            }
        ]
        """
        # journeys validation
        if "journeys" in request.data:
            all_zone_ids = set()
            journeys_required_fields = {"from_zone", "to_zone", "slot_required"}
            journeys = request.data.get("journeys")
            for journey in journeys:
                if not journeys_required_fields.issubset(journey.keys()):
                    raise ValidationError({
                        "error": __('validation.invalid', field=__("attr.journeys")),
                        "errors": {"journeys": __('validation.invalid', field=__("attr.journeys"))}
                    })

                to_zone = journey.get("to_zone")
                from_zone = journey.get("from_zone")
                # group all zone id to all_zone_ids, will used query from db to check available or not
                all_zone_ids.add(to_zone)
                all_zone_ids.add(from_zone)

            if all_zone_ids:
                existing_zones_count = TtZone.objects.filter(id__in=all_zone_ids).count()
                # if got id not found, return invalid format for journeys only
                if existing_zones_count != len(all_zone_ids):
                    raise ValidationError({
                        "error": __('validation.invalid', field=__("attr.journeys")),
                        "errors": {"journeys": __('validation.invalid', field=__("attr.journeys"))}
                    })


        # custom error after basic validation

    def post(self, request):
        # Validate input
        try:
            self.validate_request(request)
            old_new_data = {
                "old_data": None,
                "new_data": None,
            }

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

            idata = {}
            ignore_field = ["tag","journeys"]
            valid_fields = {f.column for f in TtTravelTable._meta.fields}

            for key, val in request.data.items():
                if key not in ignore_field:
                    match key:
                        case _:
                            if key in valid_fields:#for insert, key can check in default part, cause if got special handle, i can check the way to use key also
                                # default the key will same as db column name
                                idata[key] = val
            # if FE no pass in code or is null or empty, will used default code
            code = request.data.get("code")
            if not code:
                idata["code"] = get_next_available_code(TtTravelTable, "code", "MV", 10)

            idata['status'] = TtTravelTable.STATUS_TO_CODE['active']
            idata['created_by'] = request.user.id

            travel_table = TtTravelTable.objects.create(**idata)
            travel_table_id = travel_table.id

            old_new_data['new_data']=get_add_new_data(travel_table)
            new_journeys = []
            new_journey_ids = []
            if "journeys" in request.data and travel_table:
                journey_idata = [
                    TtJourney(
                        travel_table_id=travel_table_id,
                        from_zone_id=journey['from_zone'],
                        to_zone_id=journey['to_zone'],
                        slot_required=journey['slot_required']
                    )
                    for journey in request.data.get("journeys")
                ]
                new_journeys = TtJourney.objects.bulk_create(journey_idata)
                new_journey_ids = [j.id for j in new_journeys]
                old_new_data['new_data']['journey'] = [
                    {
                        "id":j.id,
                        "travel_table_id": j.travel_table_id,
                        "from_zone_id": j.from_zone_id,
                        "to_zone_id": j.to_zone_id,
                        "slot_required": j.slot_required
                    }
                    for j in new_journeys
                ]

            new_ids = request.data.get("tag", [])
            old_new_data = self.update_m2m_field(travel_table,'tag',None,new_ids,old_new_data,False,True)

            redis_travel_table_table = "travel_table"
            redis_journey_table = "journey"
            # from here make it same name as db first, got different, only do extra handle
            redis_travel_table_column = [
                "id", "code", "name", "journey_ids", "department_id"
            ]
            redis_data = {
                "insert": {},
            }
            redis_travel_table_data = {}
            for column in redis_travel_table_column:
                match column:
                    case "journey_ids":
                        redis_travel_table_data[column] = new_journey_ids
                    case _:
                        redis_travel_table_data[column] = getattr(travel_table, column)
            redis_data["insert"].setdefault(redis_travel_table_table, []).append(redis_travel_table_data)

            for new_journey in new_journeys:
                redis_data["insert"].setdefault(redis_journey_table, []).append({
                    "id": new_journey.id,
                    "from_zone_id": new_journey.from_zone_id,
                    "to_zone_id": new_journey.to_zone_id,
                    "slot_required": new_journey.slot_required
                })

            bulk_sync_to_redis(redis_client, redis_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)
            )
            remark_param = {
                "name":travel_table.name,
            }

            # 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'],
            )
            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)