import { FastifyInstance } from "fastify"
import { asc, desc, eq } from "drizzle-orm"
import { sortData } from "../utils/sort"

// Schema imports
import { accounts, units, countrys, tenants } from "../../db/schema"
import { defaultCountries } from "../utils/countries"

const TABLE_MAP: Record<string, any> = {
    accounts,
    units,
    countrys,
}

export default async function resourceRoutesSpecial(server: FastifyInstance) {

    server.get("/resource-special/:resource", async (req, reply) => {
        try {
            if (!req.user?.tenant_id) {
                return reply.code(400).send({ error: "No tenant selected" })
            }

            const { resource } = req.params as { resource: string }

            // ❌ Wenn falsche Ressource
            if (!TABLE_MAP[resource]) {
                return reply.code(400).send({ error: "Invalid special resource" })
            }

            const table = TABLE_MAP[resource]

            const { select, sort, asc: ascQuery } = req.query as {
                select?: string
                sort?: string
                asc?: string
            }

            // ---------------------------------------
            // 📌 SELECT: select-string wird in dieser Route bewusst ignoriert
            // Drizzle kann kein dynamisches Select aus String!
            // Wir geben IMMER alle Spalten zurück → kompatibel zum Frontend
            // ---------------------------------------

            if (resource === "accounts") {
                const [tenant] = await server.db
                    .select({
                        accountChart: tenants.accountChart,
                    })
                    .from(tenants)
                    .where(eq(tenants.id, Number(req.user.tenant_id)))
                    .limit(1)

                const activeAccountChart = tenant?.accountChart || "skr03"
                let data
                if (sort && (accounts as any)[sort]) {
                    const col = (accounts as any)[sort]
                    data = ascQuery === "true"
                        ? await server.db
                            .select()
                            .from(accounts)
                            .where(eq(accounts.accountChart, activeAccountChart))
                            .orderBy(asc(col))
                        : await server.db
                            .select()
                            .from(accounts)
                            .where(eq(accounts.accountChart, activeAccountChart))
                            .orderBy(desc(col))
                } else {
                    data = await server.db
                        .select()
                        .from(accounts)
                        .where(eq(accounts.accountChart, activeAccountChart))
                }

                return sortData(
                    data,
                    sort as any,
                    ascQuery === "true"
                )
            }

            let query = server.db.select().from(table)

            // ---------------------------------------
            // 📌 Sortierung
            // ---------------------------------------
            if (sort) {
                const col = (table as any)[sort]
                if (col) {
                    //@ts-ignore
                    query =
                        ascQuery === "true"
                            ? query.orderBy(asc(col))
                            : query.orderBy(desc(col))
                }
            }

            const data = await query

            if (resource === "countrys") {
                const countryMap = new Map<string, any>()

                for (const country of defaultCountries) {
                    countryMap.set(country.toLocaleLowerCase("de"), { id: country, name: country })
                }

                for (const country of data) {
                    countryMap.set(country.name.toLocaleLowerCase("de"), country)
                }

                return sortData(
                    Array.from(countryMap.values()),
                    sort || "name",
                    sort ? ascQuery === "true" : true
                )
            }

            // Falls sort clientseitig wie früher notwendig ist:
            const sorted = sortData(
                data,
                sort,
                ascQuery === "true"
            )

            return sorted
        }
        catch (err) {
            console.error(err)
            return reply.code(500).send({ error: "Internal Server Error" })
        }
    })
}
