import {defineStore} from 'pinia'
import {ref} from 'vue'
import type {Audit, AuditDetail} from "ucsd-its-frontend";
import {useUcsdAppUtils} from "ucsd-its-frontend";
import axios from "axios";
import {useItsAuthStore} from "ucsd-its-frontend";
import type {LoginUser} from "ucsd-its-frontend";


export const useAppStore = defineStore('app', () => {
    const appUtils = useUcsdAppUtils();
    const authStore = useItsAuthStore();
    const invoiceCount = ref('10');

    const initializeStore = () => {
        console.log('Initializing store')
    }

    const fetchRoles = async () : Promise<{user:LoginUser,path:string}>  => {
        try {
           const response = await axios.get(import.meta.env.VITE_USER_ROLES_API_URL, {
                headers: {
                    Authorization: `Bearer ${authStore.decryptedToken()}`
                }
            })
            const apiData = response.data[0];
            const loginUser = {
                id: apiData.PERSON_ID,
                email: apiData.EMAIL_ADDRESS,
                firstName: '',
                lastName: '',
                roles: apiData.OFC_ROLES.split(','),
                departmentName: apiData.DEPARTMENT_NAME,
                businessUnitName: apiData.BUSINESS_UNIT_NAME,
                system18Id: apiData.SYSTEM18_ID
            } as LoginUser
            return new Promise((resolve) => {
                resolve({user: loginUser,path:'/'})
            })
        } catch (error) {
            throw error
        }
    }

    const auditRecord = { // default audit record. Change this based on your domain
        auditId: 0,
        event: 'Update',
        eventIcon: '',
        nameSpace: 'edu.ucsd.its.fis.ciperb',
        auditConstituent : {
          constituentCode: 'Financial Information Systems',
        },
        details: [
            {
                detailKey: "0",
                detailValue: '',
            } as AuditDetail
        ]
    } as Audit;


    const getAuditRecord = () : Audit => {
        return <Audit>appUtils.deepClone(auditRecord)
    }


    return {
        invoiceCount,
        getAuditRecord,
        initializeStore,
        fetchRoles
    }

})
