<script>
import fetchHeaderVulnerabilityQuery from 'ee/security_dashboard/graphql/header_vulnerability.graphql';
import { convertToGraphQLId } from '~/graphql_shared/utils';
import { TYPE_VULNERABILITY } from '~/graphql_shared/constants';
import { fetchPolicies } from '~/lib/graphql';
import { s__ } from '~/locale';
import createFlash from '~/flash';
import { normalizeGraphQLVulnerability } from '../helpers';
import FalsePositiveAlert from './false_positive_alert.vue';
import VulnerabilityFooter from './footer.vue';
import VulnerabilityHeader from './header.vue';
import VulnerabilityDetails from './vulnerability_details.vue';

export default {
  components: {
    VulnerabilityHeader,
    VulnerabilityDetails,
    VulnerabilityFooter,
    FalsePositiveAlert,
  },
  props: {
    initialVulnerability: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      shouldSkipQuery: true,
      vulnerability: { ...this.initialVulnerability },
    };
  },
  computed: {
    hasFalsePositive() {
      return this.vulnerability.falsePositive;
    },
  },
  apollo: {
    vulnerability: {
      manual: true,
      query: fetchHeaderVulnerabilityQuery,
      fetchPolicy: fetchPolicies.NO_CACHE,
      variables() {
        return {
          id: convertToGraphQLId(TYPE_VULNERABILITY, this.vulnerability.id),
        };
      },
      result({ data: { vulnerability } }) {
        this.shouldSkipQuery = true;
        this.vulnerability = {
          ...this.vulnerability,
          ...normalizeGraphQLVulnerability(vulnerability),
        };
      },
      error() {
        createFlash({
          message: s__(
            'VulnerabilityManagement|Something went wrong while trying to refresh the vulnerability. Please try again later.',
          ),
        });
      },
      skip() {
        return this.shouldSkipQuery;
      },
    },
  },
  methods: {
    refreshHeader() {
      this.shouldSkipQuery = false;
      this.$apollo.queries.vulnerability.refetch();
    },
    refreshFooter(newVulnerability) {
      this.vulnerability = newVulnerability;
      this.$refs.footer.fetchDiscussions();
    },
  },
};
</script>

<template>
  <div>
    <false-positive-alert v-if="hasFalsePositive" class="gl-mt-5" />
    <vulnerability-header
      ref="header"
      :vulnerability="vulnerability"
      @vulnerability-state-change="refreshFooter"
    />
    <vulnerability-details :vulnerability="vulnerability" />
    <vulnerability-footer
      ref="footer"
      :vulnerability="vulnerability"
      @vulnerability-state-change="refreshHeader"
    />
  </div>
</template>
