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

export const ListResolutionsInput = z.object({
  companyId: z.string(),
  status: z.enum(['draft', 'published', 'archived']).optional(),
})
export const ListResolutionsOutput = z.array(
  z.object({
    resolutionId: z.string(),
    title: z.string(),
    templateKey: z.string(),
    status: z.enum(['draft', 'published', 'archived']),
    createdAt: z.string(),
    publishedAt: z.string().nullable(),
  }),
)

export const listResolutions = pikkuFunc({
  expose: true,
  description: 'List resolutions for a company, optionally filtered by status.',
  input: ListResolutionsInput,
  output: ListResolutionsOutput,
  permissions: { member: [isCompanyMember] },
  func: async ({ kysely }, { companyId, status }) => {
    let q = kysely
      .selectFrom('resolution')
      .select([
        'resolutionId',
        'title',
        'templateKey',
        'status',
        'createdAt',
        'publishedAt',
      ])
      .where('companyId', '=', companyId)
    if (status) q = q.where('status', '=', status)
    return (await q.orderBy('createdAt', 'desc').execute()) as any
  },
})
