import { z } from 'zod'
import { pikkuFunc } from '#pikku/pikku-types.gen.js'
import { isCompanyMember } from '../../lib/auth-helpers.js'

export const ListMembersInput = z.object({ companyId: z.string() })
export const ListMembersOutput = z.array(
  z.object({
    memberId: z.string(),
    userId: z.string(),
    email: z.string(),
    displayName: z.string(),
    role: z.enum(['managing_director', 'shareholder', 'angel']),
    shares: z.number().nullable(),
  }),
)

export const listMembers = pikkuFunc({
  expose: true,
  description: 'List all members of a company. Caller must be a member.',
  input: ListMembersInput,
  output: ListMembersOutput,
  permissions: { member: [isCompanyMember] },
  func: async ({ kysely }, { companyId }) => {
    const rows = await kysely
      .selectFrom('companyMember')
      .innerJoin('user', 'user.id', 'companyMember.userId')
      .select([
        'companyMember.memberId as memberId',
        'user.id as userId',
        'user.email as email',
        'user.displayName as displayName',
        'companyMember.role as role',
        'companyMember.shares as shares',
      ])
      .where('companyMember.companyId', '=', companyId)
      .orderBy('companyMember.createdAt', 'asc')
      .execute()
    return rows as any
  },
})
