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

export const CreateCompanyInput = z.object({
  name: z.string().min(2),
  registryNo: z.string().optional(),
  addressLine1: z.string().optional(),
  addressLine2: z.string().optional(),
  postcode: z.string().optional(),
  town: z.string().optional(),
  country: z.string().optional(),
  totalShares: z.number().int().nonnegative(),
  fiscalYearEnd: z.string().optional(),
})

export const CreateCompanyOutput = z.object({ companyId: z.string() })

export const createCompany = pikkuFunc({
  expose: true,
  description: 'Create a new GmbH and add the current user as managing_director.',
  input: CreateCompanyInput,
  output: CreateCompanyOutput,
  func: async ({ kysely, audit }, data, { session }) => {
    const userId = session!.userId
    const company = await kysely
      .insertInto('company')
      .values({
        name: data.name,
        registryNo: data.registryNo ?? null,
        addressLine1: data.addressLine1 ?? null,
        addressLine2: data.addressLine2 ?? null,
        postcode: data.postcode ?? null,
        town: data.town ?? null,
        country: data.country ?? null,
        totalShares: data.totalShares,
        fiscalYearEnd: data.fiscalYearEnd ?? null,
      })
      .returning(['companyId'])
      .executeTakeFirstOrThrow()

    await kysely
      .insertInto('companyMember')
      .values({
        companyId: company.companyId,
        userId,
        role: 'managing_director',
        shares: null,
      })
      .execute()

    await audit.onInsert('company', company.companyId, { ...data })
    return { companyId: company.companyId }
  },
})
