import { pikkuPermission } from '#pikku/pikku-types.gen.js'
import type { Kysely } from 'kysely'
import type { DB } from '../types/db.types.js'

async function resolveCompanyId(
  kysely: Kysely<DB>,
  data: any,
): Promise<string | undefined> {
  if (typeof data?.companyId === 'string') return data.companyId
  if (typeof data?.resolutionId === 'string') {
    const r = await kysely
      .selectFrom('resolution')
      .select(['companyId'])
      .where('resolutionId', '=', data.resolutionId)
      .executeTakeFirst()
    return r?.companyId
  }
  if (typeof data?.memberId === 'string') {
    const m = await kysely
      .selectFrom('companyMember')
      .select(['companyId'])
      .where('memberId', '=', data.memberId)
      .executeTakeFirst()
    return m?.companyId
  }
  return undefined
}

async function lookupRole(
  kysely: Kysely<DB>,
  companyId: string,
  userId: string,
): Promise<'managing_director' | 'shareholder' | 'angel' | null> {
  const m = await kysely
    .selectFrom('companyMember')
    .select(['role'])
    .where('companyId', '=', companyId)
    .where('userId', '=', userId)
    .executeTakeFirst()
  return (m?.role as any) ?? null
}

export const isCompanyMember = pikkuPermission<any>(
  async ({ kysely }, data, { session }) => {
    if (!session?.userId) return false
    const companyId = await resolveCompanyId(kysely, data)
    if (!companyId) return false
    const role = await lookupRole(kysely, companyId, session.userId)
    return role !== null
  },
)

export const isManagingDirector = pikkuPermission<any>(
  async ({ kysely }, data, { session }) => {
    if (!session?.userId) return false
    const companyId = await resolveCompanyId(kysely, data)
    if (!companyId) return false
    const role = await lookupRole(kysely, companyId, session.userId)
    return role === 'managing_director'
  },
)
