<template>

    <div class="notifyGP">

        <input type="hidden" v-model="question.answer" :name="questionName">

        <gp-practice-search
                search-url="/api/gp-addresses/search"
                search-placeholder="Search GP practice name or address"
                :user-practice="gpPractice"
                :instance-id="question.id"
                @address-updated="updateAnswer"
        ></gp-practice-search>


    </div>

</template>

<script>

import { mapGetters } from 'vuex';
import { props, computed, methods } from "../mixins/fields";
import { debounce } from 'lodash';

export default {
    name: 'notifyGp',
    mixins: [props, computed, methods],
    computed: {

        // GpAddresses package - use new GP practice getter
        ...mapGetters({
            gpPractice: 'getUserPractice'
        })

    },
    methods: {

        updateAnswer(address) {

            if(address) {
                this.question.answer = address;
            }else{
                this.question.answer = '';
            }

            this.updateQuestion(this.question);
        },

        updateQuestion: debounce(function(question) {

            question = this.validate(question);
            this.$emit('update-question', question);

        }, 200),

        validate(question) {

            let canProceed = true;

            if(typeof question.answer == 'object') {

                // Validate using new GP practice field names (address_line_1, town)
                // with fallback to legacy names (address_1, city) for existing data
                let hasAddress = question.answer?.address_line_1?.length || question.answer?.address_1?.length;
                let hasTown = question.answer?.town?.length || question.answer?.city?.length;

                if((!hasAddress && !hasTown && question.answer?.postcode) && question.is_required) {
                    canProceed = false
                }

            }else {
                if (!question.answer?.length && question.is_required) {
                    canProceed = false
                }
            }

            question.can_proceed = canProceed;

            return question;

        }


    }
}
</script>
