<script setup lang="ts">
import { inject, onBeforeMount, ref } from 'vue';
import {
	Responses,
	check_token,
	TokenInjectType,
	Admin,
	isErrorResponse
} from '@/api';
import { onBeforeRouteUpdate } from 'vue-router';
import router from '@/router';

const jwt = inject<TokenInjectType>('jwt') as TokenInjectType;

const users = ref<Responses.Admin.GetUsersEntry[]>([]);

onBeforeRouteUpdate(async () => {
	await updatePanel();
});
onBeforeMount(async () => {
	await updatePanel();
});
async function updatePanel() {
	const token = await check_token(jwt);
	if (!token) return;

	const res = await Admin.get_users(token);
	if (isErrorResponse(res)) return router.replace({ path: '/' });
	users.value = res.users;
}

async function setRole(user: number, roleStr: string) {
	const token = await check_token(jwt);
	if (!token) return;

	const res = await Admin.set_role(user, parseInt(roleStr, 10), token);
	if (isErrorResponse(res)) console.error(res.message);
	await updatePanel();
}

async function disableTfa(user: number) {
	const token = await check_token(jwt);
	if (!token) return;

	const res = await Admin.disable_tfa(user, token);
	if (isErrorResponse(res)) console.error(res.message);
	await updatePanel();
}

async function logoutUser(user: number) {
	const token = await check_token(jwt);
	if (!token) return;

	const res = await Admin.logout(user, token);
	if (isErrorResponse(res)) console.error(res.message);
	await updatePanel();
}

async function deleteUser(user: number) {
	const token = await check_token(jwt);
	if (!token) return;

	const res = await Admin.delete_user(user, token);
	if (isErrorResponse(res)) console.error(res.message);
	await updatePanel();
}
</script>

<template>
	<table>
		<tr>
			<th>Name</th>
			<th>Type</th>
			<th>Role</th>
			<th>Tfa Status</th>
			<th>Actions</th>
		</tr>
		<tr v-for="user in users" :key="user.id">
			<td>{{ user.name }}</td>
			<td>{{ user.gitlab ? 'Gitlab' : 'Password' }}</td>
			<td>
				<select @change="setRole(user.id, $event.target.value)">
					<option value="0" :selected="user.role === 0 ? true : null">
						Disabled
					</option>
					<option value="1" :selected="user.role === 1 ? true : null">
						User
					</option>
					<option value="2" :selected="user.role === 2 ? true : null">
						Admin
					</option>
				</select>
			</td>
			<td v-if="user.gitlab"></td>
			<td v-else>
				{{ user.tfaEnabled ? 'Enabled' : 'Disabled' }}
			</td>
			<td>
				<button v-if="user.tfaEnabled" @click="disableTfa(user.id)">
					Disable Tfa
				</button>
				<button @click="logoutUser(user.id)">Logout all</button>
				<button @click="deleteUser(user.id)">Delete</button>
			</td>
		</tr>
	</table>
</template>

<style scoped></style>
