// Import types from drizzle schema and shared packages
import type {
  entriesOpenAPISchema,
  feedAnalytics,
  feedAnalyticsOpenAPISchema,
  feeds,
  subscriptionsOpenAPISchema,
} from "@folo-services/drizzle"
import type { FeedOpenApiSchema as _FeedOpenApiSchema } from "@folo-services/shared"
import type { InferInsertModel, InferSelectModel } from "drizzle-orm"
import type { z } from "zod"

import type {
  EmptyResponse,
  SerializedInsertModel,
  SerializedModel,
  StructuredSuccessResponse,
} from "../../types"

type FeedOpenApiSchema = SerializedModel<_FeedOpenApiSchema>

// Re-export database types with proper date serialization
export type FeedModel = SerializedModel<InferSelectModel<typeof feeds>>
export type FeedInsert = SerializedInsertModel<InferInsertModel<typeof feeds>>
export type FeedAnalyticsModel = SerializedModel<
  InferSelectModel<typeof feedAnalytics>
>

// Entry type based on core route definitions (derived from entriesOpenAPISchema)
type EntryOpenAPISchema = z.infer<typeof entriesOpenAPISchema>
export type ParsedEntry = Omit<
  EntryOpenAPISchema,
  "feedId" | "content" | "insertedAt"
> & {
  publishedAt: Date
}

// Feed-related API request/response types
export interface FeedGetQuery {
  id?: string
  url?: string
  entriesLimit?: number
}

export type FeedGetResponse = StructuredSuccessResponse<{
  feed: FeedOpenApiSchema
  entries: ParsedEntry[]
  subscription?: SerializedModel<z.infer<typeof subscriptionsOpenAPISchema>>
  readCount: number
  subscriptionCount: number
  analytics?: SerializedModel<z.infer<typeof feedAnalyticsOpenAPISchema>>
}>

export interface FeedRefreshQuery {
  id: string
}

export type FeedRefreshResponse = EmptyResponse

export interface FeedResetQuery {
  id: string
}

export type FeedResetResponse = EmptyResponse

export interface FeedAnalyticsRequest {
  id: string[]
}

export type FeedAnalyticsResponse = StructuredSuccessResponse<{
  analytics: Record<string, SerializedModel<z.infer<typeof feedAnalyticsOpenAPISchema>>>
}>

// Feed claim types
export interface FeedClaimChallengeRequest {
  feedId: string
}

export type FeedClaimChallengeResponse = EmptyResponse

export interface FeedClaimListItem {
  feed: FeedOpenApiSchema
  subscriptionCount: number
  tipAmount: number
}

export type FeedClaimListResponse = StructuredSuccessResponse<
  FeedClaimListItem[]
>

export interface FeedClaimMessageQuery {
  feedId: string
}

export interface FeedClaimMessageData {
  content: string
  description: string
  json: string
  xml: string
}

export type FeedClaimMessageResponse =
  StructuredSuccessResponse<FeedClaimMessageData>
