import { and, eq, inArray } from "drizzle-orm"
import { FastifyInstance } from "fastify"

import { authProfileBranches, authProfiles, branches } from "../../db/schema"

function normalizeBranchIds(values: any[]): number[] {
    return [...new Set(
        values
            .map((value) => {
                if (typeof value === "number") return value
                if (typeof value === "string" && value.trim()) return Number(value)
                if (value && typeof value === "object" && "id" in value) return Number(value.id)
                return NaN
            })
            .filter((value) => Number.isFinite(value))
    )]
}

export async function enrichProfilesWithBranches(server: FastifyInstance, profiles: any[]) {
    if (!profiles.length) return profiles

    const profileIds = profiles.map((profile) => profile.id).filter(Boolean)
    if (!profileIds.length) return profiles

    const profileBranchRows = await server.db
        .select()
        .from(authProfileBranches)
        .where(inArray(authProfileBranches.profile_id, profileIds))

    const branchIds = [...new Set(profileBranchRows.map((row) => row.branch_id).filter(Boolean))]
    const branchRows = branchIds.length
        ? await server.db.select().from(branches).where(inArray(branches.id, branchIds))
        : []

    const branchMap = new Map(branchRows.map((branch) => [branch.id, branch]))
    const branchIdsByProfile = new Map<string, number[]>()

    for (const row of profileBranchRows) {
        const current = branchIdsByProfile.get(row.profile_id) || []
        current.push(row.branch_id)
        branchIdsByProfile.set(row.profile_id, current)
    }

    return profiles.map((profile) => {
        const assignedBranchIds = [...new Set(branchIdsByProfile.get(profile.id) || [])]
        return {
            ...profile,
            branch: profile.branch_id ? branchMap.get(profile.branch_id) || null : null,
            branches: assignedBranchIds
                .map((branchId) => branchMap.get(branchId))
                .filter(Boolean),
            branch_ids: assignedBranchIds,
        }
    })
}

export async function loadProfileWithBranches(server: FastifyInstance, profileId: string, tenantId: number) {
    const rows = await server.db
        .select()
        .from(authProfiles)
        .where(
            and(
                eq(authProfiles.id, profileId),
                eq(authProfiles.tenant_id, tenantId)
            )
        )
        .limit(1)

    if (!rows.length) return null

    const [profile] = await enrichProfilesWithBranches(server, rows)
    return profile
}

export async function resolveTenantBranchIds(
    server: FastifyInstance,
    tenantId: number,
    values: any[],
    primaryBranchId?: any
) {
    const normalizedPrimaryBranchId = primaryBranchId == null || primaryBranchId === ""
        ? null
        : Number(primaryBranchId)

    const requestedBranchIds = normalizeBranchIds([
        ...values,
        normalizedPrimaryBranchId,
    ])

    if (!requestedBranchIds.length) {
        return {
            primaryBranchId: normalizedPrimaryBranchId,
            branchIds: [],
        }
    }

    const validBranches = await server.db
        .select({ id: branches.id })
        .from(branches)
        .where(
            and(
                eq(branches.tenant, tenantId),
                inArray(branches.id, requestedBranchIds)
            )
        )

    const validBranchIds = validBranches.map((branch) => branch.id)

    if (validBranchIds.length !== requestedBranchIds.length) {
        throw new Error("INVALID_BRANCH_SELECTION")
    }

    if (normalizedPrimaryBranchId != null && !validBranchIds.includes(normalizedPrimaryBranchId)) {
        throw new Error("INVALID_PRIMARY_BRANCH")
    }

    return {
        primaryBranchId: normalizedPrimaryBranchId,
        branchIds: validBranchIds,
    }
}

export async function syncProfileBranches(
    server: FastifyInstance,
    profileId: string,
    branchIds: number[],
    userId?: string | null
) {
    await server.db
        .delete(authProfileBranches)
        .where(eq(authProfileBranches.profile_id, profileId))

    if (!branchIds.length) return

    await server.db
        .insert(authProfileBranches)
        .values(branchIds.map((branchId) => ({
            profile_id: profileId,
            branch_id: branchId,
            created_by: userId || null,
        })))
}
