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

export const GetCompanyInput = z.object({ companyId: z.string() })
export const GetCompanyOutput = z.object({
  companyId: z.string(),
  name: z.string(),
  registryNo: z.string().nullable(),
  addressLine1: z.string().nullable(),
  addressLine2: z.string().nullable(),
  postcode: 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(),
  myRole: z.enum(['managing_director', 'shareholder', 'angel']),
})

export const getCompany = pikkuFunc({
  expose: true,
  description: 'Fetch a company the current user is a member of.',
  input: GetCompanyInput,
  output: GetCompanyOutput,
  permissions: { member: [isCompanyMember] },
  func: async ({ kysely }, { companyId }, { session }) => {
    const role = (
      await kysely
        .selectFrom('companyMember')
        .select(['role'])
        .where('companyId', '=', companyId)
        .where('userId', '=', session!.userId)
        .executeTakeFirstOrThrow()
    ).role as 'managing_director' | 'shareholder' | 'angel'
    const c = await kysely
      .selectFrom('company')
      .selectAll()
      .where('companyId', '=', companyId)
      .executeTakeFirstOrThrow()
    const assigned = await kysely
      .selectFrom('companyMember')
      .select((eb) => eb.fn.sum<number>('shares').as('total'))
      .where('companyId', '=', companyId)
      .executeTakeFirst()
    return {
      companyId: c.companyId,
      name: c.name,
      registryNo: c.registryNo,
      addressLine1: c.addressLine1,
      addressLine2: c.addressLine2,
      postcode: c.postcode,
      town: c.town,
      country: c.country,
      totalShares: c.totalShares,
      assignedShares: Number(assigned?.total ?? 0),
      fiscalYearEnd: c.fiscalYearEnd,
      myRole: role,
    }
  },
})
