import type { Database, Tables, TablesInsert, TablesUpdate } from './database.types'
import type { SupabaseOrgId } from '../auth/multi-tenancy/org-id'

export type TableRow<T extends keyof Database['public']['Tables']> = Tables<T>
export type TableInsert<T extends keyof Database['public']['Tables']> = TablesInsert<T>
export type TableUpdate<T extends keyof Database['public']['Tables']> = TablesUpdate<T>

export type SupabaseFunction<T extends keyof Database['public']['Functions']> = Database['public']['Functions'][T]

/**
 * Strip characters that have special meaning in PostgREST filter syntax.
 * Use on user-supplied search strings before interpolating into `.or()` filter expressions.
 *
 * PostgREST uses `,` as the OR separator and `(` / `)` for logical grouping.
 * The supabase-js `.or()` method passes strings as-is with no escaping.
 */
export function sanitizePostgrestValue(value: string): string {
  return value.replace(/[,()]/g, '')
}

/**
 * Typed seam for organization-scoped Supabase filters.
 *
 * Supabase's `.eq()` accepts any string, so `.eq('organization_id', workOsOrgId)` compiles
 * cleanly even though the column holds the Supabase UUID — the exact dual-org-ID swap we want
 * to prevent. Routing org filters through this helper forces a `SupabaseOrgId`, turning that
 * swap into a compile error while leaving the query-builder chain otherwise unchanged.
 *
 * The structural `Q` constraint matches any PostgREST filter builder (its `.eq` returns `this`),
 * so the helper is independent of the supabase-js generic shape.
 *
 * @example
 * let query = supabase.from('acq_companies').select('*')
 * query = eqOrgId(query, currentSupabaseOrganizationId) // currentSupabaseOrganizationId: SupabaseOrgId
 */
export function eqOrgId<Q extends { eq(column: 'organization_id', value: string): Q }>(query: Q, id: SupabaseOrgId): Q {
  return query.eq('organization_id', id)
}

export type UpsertUserProfileResult = SupabaseFunction<'upsert_user_profile'>['Returns'][0]
