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

export const ListMyCompaniesOutput = z.array(
  z.object({
    companyId: z.string(),
    name: z.string(),
    registryNo: z.string().nullable(),
    town: z.string().nullable(),
    country: z.string().nullable(),
    totalShares: z.number().int().nonnegative(),
    assignedShares: z.number().int().nonnegative(),
    fiscalYearEnd: z.string().nullable(),
    role: z.enum(['managing_director', 'shareholder', 'angel']),
  }),
)

export const listMyCompanies = pikkuFunc({
  expose: true,
  description: 'List companies where the current user is a member.',
  output: ListMyCompaniesOutput,
  func: async ({ kysely }, _data, { session }) => {
    const rows = await kysely
      .selectFrom('companyMember as cm')
      .innerJoin('company as c', 'c.companyId', 'cm.companyId')
      .leftJoin(
        (eb) =>
          eb
            .selectFrom('companyMember')
            .select((b) => [
              'companyId',
              b.fn.sum<number>('shares').as('assignedShares'),
            ])
            .groupBy('companyId')
            .as('s'),
        (join) => join.onRef('s.companyId', '=', 'c.companyId'),
      )
      .select([
        'c.companyId as companyId',
        'c.name as name',
        'c.registryNo as registryNo',
        'c.town as town',
        'c.country as country',
        'c.totalShares as totalShares',
        's.assignedShares as assignedShares',
        'c.fiscalYearEnd as fiscalYearEnd',
        'cm.role as role',
      ])
      .where('cm.userId', '=', session!.userId)
      .orderBy('c.createdAt', 'desc')
      .execute()
    return rows.map((r) => ({
      ...r,
      assignedShares: Number(r.assignedShares ?? 0),
    })) as any
  },
})
