<template>
  <share-domain-dialog
    :dialogTitle="`「${domain.name}」の接続先管理権限設定`"
    userListTitle="接続先管理権限を持つユーザー"
    :domain="domain"
    :share-api="shareApi"
    :remove-shared-api="removeSharedApi"
    :get-shared-api="getSharedApi"
    :is-action-disable="(row) => row.id === authStore.userId"
    :model-value="modelValue"
    :action-permissions="Actions.domain.grantManage"
    @update:modelValue="updateModelValue"
    @close="close"
  />
</template>

<script setup lang="ts">
import { defineProps, defineEmits } from 'vue';
import ShareDomainDialog from 'components/ShareDomain/ShareDomainDialog.vue';
import { IUserDisplay } from '../../types/UserTypes';
import { IDomainOwnerDisplay } from '../../types/DomainTypes';
import { api } from 'boot/axios';
import { Actions } from 'boot/permissions';
import { useAuthStore } from 'src/stores/useAuthStore';
import { IResponse } from 'src/types/BaseTypes';

const authStore = useAuthStore();

interface Props {
  modelValue: boolean;
  domain: IDomainOwnerDisplay;
}

const props = defineProps<Props>();

async function shareApi(user: IUserDisplay, domain: IDomainOwnerDisplay) {
  return api.post('api/managedomain', {
    userid: user.id,
    domainid: domain.id,
  });
}

async function removeSharedApi(user: IUserDisplay, domain: IDomainOwnerDisplay) {
  return api.delete<IResponse>(`api/managedomain/${domain.id}/${user.id}`);
}

async function getSharedApi(domain: IDomainOwnerDisplay) {
  return api.get<IResponse>(`/api/managedomainuser/${domain.id}`);
}

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void;
  (e: 'close'): void;
}>();

const updateModelValue = (value: boolean) => {
  emit('update:modelValue', value);
};

const close = () => {
  emit('close');
};
</script>
