import { z } from 'zod'
import type { Db } from '../client'
import type { ZyncSubscriptionRow } from '../schema/zync-subscriptions'
import { markSubscriptionCanceled } from './subscriptions'

export const cancellationReasonSchema = z.enum([
  'too_expensive',
  'missing_feature',
  'switching_tool',
  'temporary',
  'other',
])

export type CancellationReason = z.infer<typeof cancellationReasonSchema>

export const initiateCancellationSchema = z
  .object({
    cancellationReason: cancellationReasonSchema.optional(),
    cancellationReasonFreetext: z.string().trim().max(2000).optional(),
  })
  .strict()

export type InitiateCancellationInput = z.infer<typeof initiateCancellationSchema>

export type RetentionOfferType = 'none'

export interface RetentionOffer {
  type: RetentionOfferType
}

export async function retentionOffer(): Promise<RetentionOffer> {
  return { type: 'none' }
}

export async function initiateCancellation(
  db: Db,
  tenantId: string,
  _actorUserId: string,
  input: InitiateCancellationInput,
): Promise<{ offer: RetentionOffer; subscription: ZyncSubscriptionRow }> {
  const subscription = await markSubscriptionCanceled(db, tenantId, {
    cancellationReason: input.cancellationReason ?? null,
    cancellationReasonFreetext: input.cancellationReasonFreetext ?? null,
  })
  if (!subscription) {
    throw new Error('initiateCancellation: no subscription found for tenant')
  }
  return {
    offer: { type: 'none' },
    subscription,
  }
}

export async function completeCancellation(
  db: Db,
  tenantId: string,
  _actorUserId: string,
): Promise<ZyncSubscriptionRow> {
  const subscription = await markSubscriptionCanceled(db, tenantId)
  if (!subscription) {
    throw new Error('completeCancellation: no subscription found for tenant')
  }
  return subscription
}
