<script>
import { DASHBOARD_TYPES } from 'ee/security_dashboard/store/constants';
import VulnerabilityCounts from './vulnerability_counts.vue';
import VulnerabilityListGraphql from './vulnerability_list_graphql.vue';
import VulnerabilityFilters from './vulnerability_filters.vue';
import {
  FIELDS,
  FILTERS,
  FIELD_PRESETS,
  FILTER_PRESETS,
  REPORT_TAB,
  REPORT_TYPE_PRESETS,
} from './constants';

export default {
  components: {
    VulnerabilityCounts,
    VulnerabilityListGraphql,
    VulnerabilityFilters,
  },
  inject: ['dashboardType', 'canAdminVulnerability'],
  props: {
    type: {
      type: String,
      required: true,
    },
    query: {
      type: Object,
      required: true,
    },
    showProjectFilter: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  data() {
    return {
      graphqlFilters: undefined,
    };
  },
  computed: {
    filtersToShow() {
      // Special case for project-level development tab, it needs to show the new vendor scanner
      // filter instead of the old simple filter. This is a temporary workaround until this issue is
      // addressed: https://gitlab.com/gitlab-org/gitlab/-/issues/332727 after which all report
      // levels will use the new vendor scanner filter and this check can be removed.
      const type =
        this.type === REPORT_TAB.DEVELOPMENT && this.dashboardType === DASHBOARD_TYPES.PROJECT
          ? REPORT_TAB.DEVELOPMENT_PROJECT
          : this.type;

      return [...FILTER_PRESETS[type], ...(this.showProjectFilter ? [FILTERS.PROJECT] : [])];
    },
    fieldsToShow() {
      return [
        // Add the checkbox field if the user can use the bulk select feature.
        ...(this.canAdminVulnerability ? [FIELDS.CHECKBOX] : []),
        ...FIELD_PRESETS[this.type],
      ];
    },
  },
  methods: {
    updateGraphqlFilters(graphqlFilters) {
      this.graphqlFilters = graphqlFilters;

      if (this.type === REPORT_TAB.DEVELOPMENT && (graphqlFilters.reportType?.length || 0) <= 0) {
        this.graphqlFilters.reportType = REPORT_TYPE_PRESETS.DEVELOPMENT;
      } else if (this.type === REPORT_TAB.OPERATIONAL) {
        this.graphqlFilters.reportType = REPORT_TYPE_PRESETS.OPERATIONAL;
      }
    },
  },
};
</script>

<template>
  <div>
    <vulnerability-counts class="gl-mt-7" :filters="graphqlFilters" />

    <vulnerability-filters
      :filters="filtersToShow"
      class="security-dashboard-filters gl-mt-7"
      @filters-changed="updateGraphqlFilters"
    />

    <vulnerability-list-graphql
      class="gl-mt-6"
      :query="query"
      :fields="fieldsToShow"
      :filters="graphqlFilters"
      :show-project-namespace="showProjectFilter"
    />
  </div>
</template>
