import { and, eq, sql } from "drizzle-orm";
import { cards, 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 TopEstablishment = {
	id: string;
	name: string;
	amount: number;
	occurrences: number;
	logo: string | null;
};

export type TopEstablishmentsData = {
	establishments: TopEstablishment[];
};

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

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

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

	return true;
};

export async function fetchTopEstablishments(
	userId: string,
	period: string,
): Promise<TopEstablishmentsData> {
	const adminPayerId = await getAdminPayerId(userId);
	if (!adminPayerId) {
		return { establishments: [] };
	}

	const rows = await db
		.select({
			name: transactions.name,
			totalAmount: sql<number>`coalesce(sum(${transactions.amount}), 0)`,
			occurrences: sql<number>`count(${transactions.id})`,
			logo: sql<
				string | null
			>`max(coalesce(${cards.logo}, ${financialAccounts.logo}))`,
		})
		.from(transactions)
		.leftJoin(cards, eq(transactions.cardId, cards.id))
		.leftJoin(
			financialAccounts,
			eq(transactions.accountId, financialAccounts.id),
		)
		.where(
			and(
				...buildDashboardAdminPeriodFilters({
					userId,
					period,
					adminPayerId,
				}),
				eq(transactions.transactionType, "Despesa"),
				excludeAutoGeneratedEntryNotes(),
			),
		)
		.groupBy(transactions.name)
		.orderBy(
			sql`count(${transactions.id}) DESC`,
			sql`ABS(sum(${transactions.amount})) DESC`,
		)
		.limit(10);

	const establishments = rows
		.filter((row: (typeof rows)[number]) =>
			shouldIncludeEstablishment(row.name),
		)
		.map(
			(row: (typeof rows)[number]): TopEstablishment => ({
				id: row.name,
				name: row.name,
				amount: Math.abs(toNumber(row.totalAmount)),
				occurrences: Number(row.occurrences ?? 0),
				logo: row.logo ?? null,
			}),
		);

	return {
		establishments,
	};
}
