import { pikkuSessionlessFunc } from '#pikku/pikku-types.gen.js'
import { sql } from 'kysely'

export const getInstitutionMatches = pikkuSessionlessFunc<
  { query: string },
  any
>(async ({ kysely }, { query }) => {
  const result = await sql`
      SELECT
      institution_id,
      main_name_short,
      main_name_german,
      alias_name_short,
      alias_name_german,
      alias_type,
      GREATEST(
        similarity(main_name_short, ${query}),
        similarity(main_name_german, ${query}),
        similarity(alias_name_short, ${query}),
        similarity(alias_name_german, ${query})
      ) AS match_score
    FROM institutions.institution_search
    WHERE
      main_name_short % ${query}
      OR main_name_german % ${query}
      OR alias_name_short % ${query}
      OR alias_name_german % ${query}
    ORDER BY match_score DESC
    LIMIT 5;
  `.execute(kysely)

  return result.rows
})

export const getDegreeMatches = pikkuSessionlessFunc<
  { query: string },
  any
>(async ({ kysely }, { query }) => {
  const result = await sql`
    SELECT 
      degree_id,
      main_name_short,
      main_name_german,
      alias_name_short,
      alias_name_german,
      alias_type,
      GREATEST(
        similarity(main_name_short, ${query}),
        similarity(main_name_german, ${query}),
        similarity(alias_name_short, ${query}),
        similarity(alias_name_german, ${query})
      ) AS match_score
    FROM institutions.degree_search
    WHERE
      main_name_short % ${query}
      OR main_name_german % ${query}
      OR alias_name_short % ${query}
      OR alias_name_german % ${query}
    ORDER BY match_score DESC
    LIMIT 5;
  `.execute(kysely)

  return result.rows
})