import { and, desc, eq, inArray } from "drizzle-orm";
import {
	cards,
	categories,
	financialAccounts,
	transactions,
} from "@/db/schema";
import {
	buildDashboardAdminPeriodFilters,
	excludeAutoGeneratedEntryNotes,
} from "@/features/dashboard/transaction-filters";
import { db } from "@/shared/lib/db";
import { getAdminPayerId } from "@/shared/lib/payers/get-admin-id";
import { safeToNumber as toNumber } from "@/shared/utils/number";

export type CategoryOption = {
	id: string;
	name: string;
	type: string;
};

export type CategoryTransaction = {
	id: string;
	name: string;
	amount: number;
	purchaseDate: Date;
	logo: string | null;
};

export type PurchasesByCategoryData = {
	categories: CategoryOption[];
	transactionsByCategory: Record<string, CategoryTransaction[]>;
};

const shouldIncludeTransaction = (name: string) => {
	const normalized = name.trim().toLowerCase();

	if (normalized === "saldo inicial") {
		return false;
	}

	if (normalized.includes("fatura")) {
		return false;
	}

	return true;
};

export async function fetchPurchasesByCategory(
	userId: string,
	period: string,
): Promise<PurchasesByCategoryData> {
	const adminPayerId = await getAdminPayerId(userId);
	if (!adminPayerId) {
		return { categories: [], transactionsByCategory: {} };
	}

	const transactionsRows = await db
		.select({
			id: transactions.id,
			name: transactions.name,
			amount: transactions.amount,
			purchaseDate: transactions.purchaseDate,
			categoryId: transactions.categoryId,
			categoryName: categories.name,
			categoryType: categories.type,
			cardLogo: cards.logo,
			accountLogo: financialAccounts.logo,
		})
		.from(transactions)
		.innerJoin(categories, eq(transactions.categoryId, categories.id))
		.leftJoin(cards, eq(transactions.cardId, cards.id))
		.leftJoin(
			financialAccounts,
			eq(transactions.accountId, financialAccounts.id),
		)
		.where(
			and(
				...buildDashboardAdminPeriodFilters({
					userId,
					period,
					adminPayerId,
				}),
				inArray(categories.type, ["despesa", "receita"]),
				excludeAutoGeneratedEntryNotes(),
			),
		)
		.orderBy(desc(transactions.purchaseDate));

	const transactionsByCategory: Record<string, CategoryTransaction[]> = {};
	const categoriesMap = new Map<string, CategoryOption>();

	for (const row of transactionsRows) {
		const categoryId = row.categoryId;

		if (!categoryId) {
			continue;
		}

		if (!shouldIncludeTransaction(row.name)) {
			continue;
		}

		// Adiciona a categoria ao mapa se ainda não existir
		if (!categoriesMap.has(categoryId)) {
			categoriesMap.set(categoryId, {
				id: categoryId,
				name: row.categoryName,
				type: row.categoryType,
			});
		}

		const entry: CategoryTransaction = {
			id: row.id,
			name: row.name,
			amount: Math.abs(toNumber(row.amount)),
			purchaseDate: row.purchaseDate,
			logo: row.cardLogo ?? row.accountLogo ?? null,
		};

		if (!transactionsByCategory[categoryId]) {
			transactionsByCategory[categoryId] = [];
		}

		const categoryTransactions = transactionsByCategory[categoryId];
		if (categoryTransactions && categoryTransactions.length < 10) {
			categoryTransactions.push(entry);
		}
	}

	// Ordena as categories: receitas primeiro, depois despesas (alfabeticamente dentro de cada tipo)
	const categoryList = Array.from(categoriesMap.values()).sort((a, b) => {
		// Receita vem antes de despesa
		if (a.type !== b.type) {
			return a.type === "receita" ? -1 : 1;
		}
		// Dentro do mesmo tipo, ordena alfabeticamente
		return a.name.localeCompare(b.name);
	});

	return {
		categories: categoryList,
		transactionsByCategory,
	};
}
