import { FastifyInstance } from "fastify"

import {
    authTenantUsers,
    authUsers,
    authProfiles,
    tenants
} from "../../../db/schema"

import {and, eq, inArray} from "drizzle-orm"
import { enrichProfilesWithBranches } from "../../utils/profileBranches"
import { enrichProfilesWithTeams } from "../../utils/profileTeams"


export default async function tenantRoutesInternal(server: FastifyInstance) {


    // -------------------------------------------------------------
    // GET CURRENT TENANT
    // -------------------------------------------------------------
    server.get("/tenant/:id", async (req) => {
        //@ts-ignore
        const tenant = (await server.db.select().from(tenants).where(eq(tenants.id,req.params.id)).limit(1))[0]

        return tenant
    })


    // -------------------------------------------------------------
    // TENANT USERS (auth_users + auth_profiles)
    // -------------------------------------------------------------
    server.get("/tenant/users", async (req, reply) => {
        try {
            const authUser = req.user
            if (!authUser) return reply.code(401).send({ error: "Unauthorized" })

            const tenantId = authUser.tenant_id

            // 1) auth_tenant_users → user_ids
            const tenantUsers = await server.db
                .select()
                .from(authTenantUsers)
                .where(eq(authTenantUsers.tenant_id, tenantId))

            const userIds = tenantUsers.map(u => u.user_id)

            if (!userIds.length) {
                return { tenant_id: tenantId, users: [] }
            }

            // 2) auth_users laden
            const users = await server.db
                .select()
                .from(authUsers)
                .where(inArray(authUsers.id, userIds))

            // 3) auth_profiles pro Tenant laden
            const profileRows = await server.db
                .select()
                .from(authProfiles)
                .where(
                    and(
                        eq(authProfiles.tenant_id, tenantId),
                        inArray(authProfiles.user_id, userIds)
                    ))
            const profilesWithBranches = await enrichProfilesWithBranches(server, profileRows)
            const profiles = await enrichProfilesWithTeams(server, profilesWithBranches)

            const combined = users.map(u => {
                const profile = profiles.find(p => p.user_id === u.id)
                return {
                    id: u.id,
                    email: u.email,
                    profile,
                    full_name: profile?.full_name ?? null
                }
            })

            return { tenant_id: tenantId, users: combined }

        } catch (err) {
            console.error("/tenant/users ERROR:", err)
            return reply.code(500).send({ error: "Internal Server Error" })
        }
    })



    // -------------------------------------------------------------
    // TENANT PROFILES
    // -------------------------------------------------------------
    server.get("/tenant/:id/profiles", async (req, reply) => {
        try {
            // @ts-ignore
            const tenantId = req.params.id
            if (!tenantId) return reply.code(401).send({ error: "Unauthorized" })

            const profileRows = await server.db
                .select()
                .from(authProfiles)
                .where(eq(authProfiles.tenant_id, tenantId))

            const profilesWithBranches = await enrichProfilesWithBranches(server, profileRows)
            return await enrichProfilesWithTeams(server, profilesWithBranches)

        } catch (err) {
            console.error("/tenant/profiles ERROR:", err)
            return reply.code(500).send({ error: "Internal Server Error" })
        }
    })

}
