import { date } from "quasar";
import { computed, ref } from "vue";
import { defineStore } from "pinia";
import { useTimesheetStore } from "src/stores/timesheet-store";
import { Expense } from "src/modules/timesheets/models/expense.models";
import { ExpenseService } from "src/modules/timesheets/services/expense-service";
import { computeCRC32Base64 } from "src/utils/crc-encoder";

export const useExpensesStore = defineStore('expenses', () => {
    const timesheet_store = useTimesheetStore();
    const is_open = ref(false);
    const is_loading = ref(false);
    const is_showing_create_form = ref(false);
    const mode = ref<'create' | 'update' | 'delete'>('create');
    const current_expense = ref<Expense>(new Expense(date.formatDate(new Date(), 'YYYY-MM-DD')));
    const initial_expense = ref<Expense>(new Expense(date.formatDate(new Date(), 'YYYY-MM-DD')));
    const is_save_disabled = computed(() => JSON.stringify(current_expense.value) === JSON.stringify(initial_expense.value))

    const open = (): void => {
        is_open.value = true;
        is_showing_create_form.value = false;
        if (timesheet_store.pay_period !== undefined) {
            current_expense.value = new Expense(date.formatDate(new Date(), 'YYYY-MM-DD'));
            initial_expense.value = new Expense(date.formatDate(new Date(), 'YYYY-MM-DD'));
        }
        mode.value = 'create';
    }

    const close = () => {
        is_open.value = false;
        is_showing_create_form.value = false;
    };

    const upsertExpense = async (expense: Expense, email?: string): Promise<boolean> => {
        try {
            if (expense.id < 0) {
                const data = await ExpenseService.createExpense(expense);
                return data.success;
            }
            const data = await ExpenseService.updateExpense(expense, email);
            return data.success;
        } catch (err) {
            // setErrorFrom(err);
            console.error(err);
            return false;
        }
    };

    const deleteExpenseById = async (expense_id: number): Promise<boolean> => {
        const data = await ExpenseService.deleteExpenseById(expense_id);
        return data.success;
    }

    const uploadAttachment = async (file: File) => {
        try {
            const checksum = await computeCRC32Base64(file);
            const presignedUrlResponse = await ExpenseService.getPresignedUploadURL(file, checksum);
            
            if (presignedUrlResponse.success && presignedUrlResponse.data) {
                const { url, key } = JSON.parse(presignedUrlResponse.data);
                console.log('key: ', key);

                await ExpenseService.uploadAttachmentWithPresignedUrl(file, url);
            }
        } catch (error) {
            console.error(error);
        }
    }

    return {
        is_open,
        is_loading,
        is_showing_create_form,
        mode,
        current_expense,
        initial_expense,
        is_save_disabled,
        open,
        upsertExpense,
        deleteExpenseById,
        close,
        uploadAttachment,
    };
});