import { CreateTransactionDTO, Transaction, UpdateTransactionDTO } from "@/models/transaction";
import { TransactionKind, TransactionType } from "@/models/enums";
import { categoriesService } from "@/services/categories-service";
import { User } from "@/models/user";
import api from "@/network/axiosSetup";

// const spaceStore = useSpaceStore();
function toDateOnly(d: Date): string {
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${y}-${m}-${day}`;
}

export interface TransactionFilters {
    query: string | null
    type: TransactionType | null
    kind: TransactionKind | null
    categoriesIds: number[] | null
    dateFrom: string | Date | null
    dateTo: string | Date | null
    isDone: boolean | null
    offset: number | null
    limit: number | null
    sorts: { sortBy: string; sortDirection: string }[]
}

enum SortDirection {
    ASC = "ASC",
    DESC = 'DESC'
}

async function getTransactions(spaceId: number, filters: TransactionFilters): Promise<Transaction[]> {
    try {
        let response = await api.post(`/spaces/${spaceId}/transactions/_search`, filters);
        return response.data;
    } catch (error) {
        console.error(error);
        throw error;
    }
}

async function getTransaction(spaceId: number, id: number): Promise<Transaction> {
    try {
        let response = await api.get(`/spaces/${spaceId}/transactions/${id}`);
        return response.data;
    } catch (error) {
        console.error(error);
        throw error;
    }

}

async function createTransaction(spaceId: number, tx: CreateTransactionDTO): Promise<number> {
    try {
        tx.date = toDateOnly(tx.date)
        return await api.post(`/spaces/${spaceId}/transactions`, tx)
    } catch (error) {
        console.error(error);
        throw error;
    }
}

async function updateTransaction(spaceId: number, txId: number, tx: UpdateTransactionDTO): Promise<void> {
    try {
        tx.date = toDateOnly(tx.date)
        return await api.put(`/spaces/${spaceId}/transactions/${txId}`, tx)
    } catch (error) {
        console.error(error);
        throw error;
    }
}

async function deleteTransaction(spaceId: number, txId: number): Promise<void> {
    try {
        return await api.delete(`/spaces/${spaceId}/transactions/${txId}`);
    } catch (error) {
        console.error(error);
        throw error;
    }
}

export const TransactionService = {
    getTransactions, getTransaction, createTransaction, updateTransaction, deleteTransaction,
}