import type { components } from './generated/schema'

export type User = Omit<components['schemas']['AuthMeResponse'], 'userId' | 'displayName' | 'platformRoles'> & {
  userId: string
  displayName: string
  email?: string
  avatarUrl?: string
  oauthProvider?: string
  platformRoles: string[]
}

export type OAuthProvider = Omit<components['schemas']['AuthProviderResponse'], 'id' | 'name' | 'authorizationUrl'> & {
  id: string
  name: string
  authorizationUrl: string
}

type AuthMethodSchema = components['schemas']['AuthMethodResponse']

export type AuthMethod = Omit<
  AuthMethodSchema,
  'id' | 'methodType' | 'provider' | 'displayName' | 'actionUrl'
> & {
  id: string
  methodType: NonNullable<AuthMethodSchema['methodType']>
  provider: string
  displayName: string
  actionUrl: string
}

export type ApiToken = Omit<components['schemas']['TokenSummaryResponse'], 'id' | 'name' | 'tokenPrefix' | 'createdAt'> & {
  id: number
  name: string
  tokenPrefix: string
  createdAt: string
  expiresAt?: string
  lastUsedAt?: string
}

export type CreateTokenRequest = Omit<components['schemas']['TokenCreateRequest'], 'name'> & {
  name: string
  scopes?: string[]
  expiresAt?: string
}

export type CreateTokenResponse = Omit<components['schemas']['TokenCreateResponse'], 'token' | 'id' | 'name' | 'tokenPrefix' | 'createdAt'> & {
  token: string
  id: number
  name: string
  tokenPrefix: string
  createdAt: string
  expiresAt?: string
}

export interface LocalLoginRequest {
  username: string
  password: string
}

export interface LocalRegisterRequest extends LocalLoginRequest {
  email: string
}

export interface ChangePasswordRequest {
  currentPassword: string
  newPassword: string
}

type IdentityLinkIntentSchema = components['schemas']['IdentityLinkIntentResponse']
type IdentityLinkBindingSchema = components['schemas']['IdentityLinkBindingResponse']
type IdentityLinkProviderSchema = components['schemas']['IdentityLinkProviderResponse']

export type IdentityLinkOperation = NonNullable<IdentityLinkIntentSchema['operation']>
export type IdentityLinkIntentStatus = NonNullable<IdentityLinkIntentSchema['status']>
export type IdentityProviderLoginMethodType =
  NonNullable<IdentityLinkBindingSchema['methodTypes']>[number]

export type IdentityLinkIntent = Omit<
  IdentityLinkIntentSchema,
  'id' | 'operation' | 'status' | 'providerCode' | 'expiresAt'
> & {
  id: string
  operation: IdentityLinkOperation
  status: IdentityLinkIntentStatus
  providerCode: string
  targetBindingId?: number
  expiresAt: string
}

export type IdentityLinkBinding = Omit<
  IdentityLinkBindingSchema,
  'bindingId' | 'providerCode' | 'displayName' | 'methodTypes' | 'usable' | 'canUnlink'
> & {
  bindingId: number
  providerCode: string
  displayName: string
  methodTypes: IdentityProviderLoginMethodType[]
  usable: boolean
  canUnlink: boolean
}

export type IdentityLinkProvider = Omit<
  IdentityLinkProviderSchema,
  'providerCode' | 'displayName' | 'methodTypes'
> & {
  providerCode: string
  displayName: string
  methodTypes: IdentityProviderLoginMethodType[]
}

export interface IdentityLinkAccountState {
  localPasswordEnabled: boolean
  linkedProviders: IdentityLinkBinding[]
  availableProviders: IdentityLinkProvider[]
}

export type IdentityLinkCredentialRequest =
  components['schemas']['IdentityLinkTargetCredentialRequest']

export interface PasswordResetRequest {
  email: string
}

export interface PasswordResetConfirmRequest {
  email: string
  code: string
  newPassword: string
}

export type CreateNamespaceRequest = Omit<components['schemas']['NamespaceRequest'], 'slug' | 'displayName'> & {
  slug: string
  displayName: string
  description?: string
}

type AccountMergeAuthenticationMethodSchema =
  components['schemas']['AccountMergeAuthenticationMethodResponse']
type AccountMergeCapabilitiesSchema =
  components['schemas']['AccountMergeCapabilitiesResponse']
type AccountMergeIntentSchema =
  components['schemas']['AccountMergeIntentResponse']
type AccountMergePreviewSchema =
  components['schemas']['AccountMergePreviewResponse']
type AccountMergeCompletionSchema =
  components['schemas']['AccountMergeCompletionResponse']

export type AccountMergeMethodType =
  | 'LOCAL_PASSWORD'
  | 'OAUTH_REDIRECT'
  | 'CAS_REDIRECT'
  | 'DIRECT_PASSWORD'

export type AccountMergeIntentStatus =
  NonNullable<AccountMergeIntentSchema['status']>

export type AccountMergeAuthenticationMethod = Omit<
  AccountMergeAuthenticationMethodSchema,
  'providerCode' | 'displayName' | 'methodType'
> & {
  providerCode: string
  displayName: string
  methodType: AccountMergeMethodType
}

export type AccountMergeCapabilities = Omit<
  AccountMergeCapabilitiesSchema,
  'enabled' | 'primaryMethods' | 'secondaryMethods'
> & {
  enabled: boolean
  primaryMethods: AccountMergeAuthenticationMethod[]
  secondaryMethods: AccountMergeAuthenticationMethod[]
}

export type AccountMergeIntent = Omit<
  AccountMergeIntentSchema,
  'id' | 'status' | 'expiresAt' | 'secondaryMethods'
> & {
  id: string
  status: AccountMergeIntentStatus
  expiresAt: string
  secondaryMethods: AccountMergeAuthenticationMethod[]
}

export interface AccountMergeCredentialRequest {
  username: string
  password: string
}

export interface AccountMergeNamespaceChange {
  namespaceId: number
  namespaceSlug: string
  primaryRole?: string
  secondaryRole?: string
  resultingRole?: string
  blocked: boolean
}

export interface AccountMergeTokenSummary {
  name: string
  prefix: string
}

export interface AccountMergeSocialSummary {
  starsMoved: number
  duplicateStarsDiscarded: number
  ratingsMoved: number
  duplicateRatingsDiscarded: number
  subscriptionsMoved: number
  duplicateSubscriptionsDiscarded: number
  discardedRatings: AccountMergeDiscardedRating[]
}

export interface AccountMergeDiscardedRating {
  skillId: number
  score: number
}

export interface AccountMergeNotificationSummary {
  notificationsMoved: number
  preferencesMoved: number
  duplicatePreferencesDiscarded: number
  governanceNotificationsMoved: number
}

export interface AccountMergeConflict {
  code: string
  resource: string
  suggestedAction: string
}

export type AccountMergePreview = Omit<
  AccountMergePreviewSchema,
  | 'intentId'
  | 'status'
  | 'previewVersion'
  | 'expiresAt'
  | 'confirmable'
  | 'identityProviders'
  | 'localCredentialAction'
  | 'blockedPlatformRoles'
  | 'namespaceChanges'
  | 'apiTokensToRevoke'
  | 'skillOwnershipCount'
  | 'social'
  | 'notifications'
  | 'conflicts'
> & {
  intentId: string
  status: AccountMergeIntentStatus
  previewVersion: number
  expiresAt: string
  confirmable: boolean
  identityProviders: string[]
  localCredentialAction: string
  blockedPlatformRoles: string[]
  namespaceChanges: AccountMergeNamespaceChange[]
  apiTokensToRevoke: AccountMergeTokenSummary[]
  skillOwnershipCount: number
  social: AccountMergeSocialSummary
  notifications: AccountMergeNotificationSummary
  conflicts: AccountMergeConflict[]
}

export type AccountMergeCompletion = Omit<
  AccountMergeCompletionSchema,
  'intentId' | 'status' | 'completedAt'
> & {
  intentId: string
  status: AccountMergeIntentStatus
  completedAt: string
}

// Namespace types
export type NamespaceStatus = 'ACTIVE' | 'FROZEN' | 'ARCHIVED' | string
export type NamespaceRole = 'OWNER' | 'ADMIN' | 'MEMBER' | string

export interface Namespace {
  id: number
  slug: string
  displayName: string
  description?: string
  type: 'GLOBAL' | 'TEAM'
  avatarUrl?: string
  status: NamespaceStatus
  createdAt: string
  updatedAt?: string
}

export interface ManagedNamespace extends Namespace {
  createdBy?: string
  currentUserRole?: NamespaceRole
  immutable: boolean
  canFreeze: boolean
  canUnfreeze: boolean
  canArchive: boolean
  canRestore: boolean
  canDelete: boolean
}

export interface NamespaceMember {
  id: number
  userId: string
  displayName?: string
  email?: string
  role: NamespaceRole
  createdAt: string
}

export interface NamespaceCandidateUser {
  userId: string
  displayName: string
  email?: string
  status: string
}

export interface BatchMemberResult {
  userId: string
  role: string
  success: boolean
  error?: string
}

export interface BatchMemberResponse {
  totalCount: number
  successCount: number
  failureCount: number
  results: BatchMemberResult[]
}

// Skill types
export interface SkillSummary {
  id: number
  slug: string
  displayName: string
  summary?: string
  visibility?: string
  status?: string
  downloadCount: number
  starCount: number
  ratingAvg?: number
  ratingCount: number
  namespace: string
  updatedAt: string
  canSubmitPromotion: boolean
  headlineVersion?: SkillLifecycleVersion
  publishedVersion?: SkillLifecycleVersion
  ownerPreviewVersion?: SkillLifecycleVersion
  resolutionMode?: string
}

export type LabelItem = Omit<components['schemas']['SkillLabelDto'], 'slug' | 'type' | 'displayName'> & {
  slug: string
  type: 'RECOMMENDED' | 'PRIVILEGED' | string
  displayName: string
}

export type LabelTranslation = Omit<components['schemas']['LabelTranslationResponse'], 'locale' | 'displayName'> & {
  locale: string
  displayName: string
}

export type LabelDefinition = Omit<
  components['schemas']['LabelDefinitionResponse'],
  'slug' | 'type' | 'translations' | 'sortOrder' | 'visibleInFilter'
> & {
  slug: string
  type: 'RECOMMENDED' | 'PRIVILEGED' | string
  visibleInFilter: boolean
  sortOrder: number
  translations: LabelTranslation[]
}

export interface AdminLabelInput {
  slug: string
  type: 'RECOMMENDED' | 'PRIVILEGED'
  visibleInFilter: boolean
  sortOrder: number
  translations: LabelTranslation[]
}

export interface SkillLifecycleVersion {
  id: number
  version: string
  status: string
}

export interface SkillDetail {
  id: number
  slug: string
  displayName: string
  ownerId?: string
  ownerDisplayName?: string
  summary?: string
  visibility: string
  status: string
  downloadCount: number
  starCount: number
  ratingAvg?: number
  ratingCount: number
  hidden: boolean
  namespace: string
  labels?: LabelItem[]
  canManageLifecycle: boolean
  canSubmitPromotion: boolean
  canInteract: boolean
  canReport: boolean
  headlineVersion?: SkillLifecycleVersion
  publishedVersion?: SkillLifecycleVersion
  ownerPreviewVersion?: SkillLifecycleVersion
  ownerPreviewReviewComment?: string
  resolutionMode?: string
}

export interface SubmitPromotionRequest {
  sourceSkillId: number
  sourceVersionId: number
  targetNamespaceId: number
}

export interface SkillVersion {
  id: number
  version: string
  status: string
  changelog?: string
  fileCount: number
  totalSize: number
  publishedAt: string
  downloadAvailable: boolean
}

export interface SkillVersionDetail {
  id: number
  version: string
  status: string
  changelog?: string
  fileCount: number
  totalSize: number
  publishedAt: string
  parsedMetadataJson?: string
  manifestJson?: string
}

export interface SkillFile {
  id: number
  filePath: string
  fileSize: number
  contentType: string
  sha256: string
}

export interface SkillVersionCompareLine {
  type: 'CONTEXT' | 'ADD' | 'DELETE' | string
  content: string
  oldLineNumber: number | null
  newLineNumber: number | null
}

export interface SkillVersionCompareHunk {
  oldStart: number
  oldLines: number
  newStart: number
  newLines: number
  lines: SkillVersionCompareLine[]
}

export interface SkillVersionCompareFile {
  path: string
  changeType: 'ADDED' | 'MODIFIED' | 'REMOVED' | string
  oldSize: number | null
  newSize: number | null
  binary: boolean
  truncated: boolean
  hunks: SkillVersionCompareHunk[]
}

export interface SkillVersionCompareSummary {
  totalFiles: number
  addedFiles: number
  modifiedFiles: number
  removedFiles: number
  addedLines: number
  removedLines: number
}

export interface SkillVersionCompare {
  from: string
  to: string
  summary: SkillVersionCompareSummary
  files: SkillVersionCompareFile[]
}

export interface SkillTag {
  id: number
  tagName: string
  versionId: number
  createdAt: string
}

// Search and pagination
export interface SearchParams {
  q?: string
  namespace?: string
  label?: string
  sort?: string
  page?: number
  size?: number
  starredOnly?: boolean
}

export interface PagedResponse<T> {
  items: T[]
  total: number
  page: number
  size: number
}

// Publish
export interface PublishResult {
  skillId: number
  namespace: string
  slug: string
  version: string
  status: string
  fileCount: number
  totalSize: number
}

export interface SkillDeleteResult {
  skillId?: number
  namespace?: string
  slug?: string
  deleted?: boolean
}

export interface ReviewTask {
  id: number
  skillVersionId: number
  namespace: string
  skillSlug: string
  version: string
  status: 'PENDING' | 'APPROVED' | 'REJECTED'
  submittedBy: string
  submittedByName?: string
  reviewedBy?: string
  reviewedByName?: string
  reviewComment?: string
  submittedAt: string
  reviewedAt?: string
}

export interface ReviewSkillDetail {
  skill: SkillDetail
  versions: SkillVersion[]
  files: SkillFile[]
  documentationPath?: string
  documentationContent?: string
  downloadUrl: string
  activeVersion: string
}

export type PromotionStatus = 'PENDING' | 'APPROVED' | 'REJECTED'
export type PromotionSortDirection = 'ASC' | 'DESC'
export type PromotionSortBy = 'reviewedAt'

export interface PromotionTask {
  id: number
  sourceSkillId: number
  sourceSkillDisplayName: string
  sourceSkillSummary?: string | null
  sourceNamespace: string
  sourceSkillSlug: string
  sourceVersion: string
  sourceVersionFileCount: number
  sourceVersionTotalSize: number
  sourceSkillDownloadCount: number
  sourceSkillStarCount: number
  targetNamespace: string
  targetSkillId?: number | null
  status: PromotionStatus
  submittedBy: string
  submittedByName?: string | null
  reviewedBy?: string | null
  reviewedByName?: string | null
  reviewComment?: string | null
  submittedAt: string
  reviewedAt?: string | null
}

export interface SkillReport {
  id: number
  skillId: number
  namespace?: string
  skillSlug?: string
  skillDisplayName?: string
  reporterId: string
  reason: string
  details?: string
  status: 'PENDING' | 'RESOLVED' | 'DISMISSED' | string
  handledBy?: string
  handleComment?: string
  createdAt: string
  handledAt?: string
}

export type ReportDisposition = 'RESOLVE_ONLY' | 'RESOLVE_AND_HIDE' | 'RESOLVE_AND_ARCHIVE'

export interface GovernanceSummary {
  pendingReviews: number
  pendingPromotions: number
  pendingReports: number
  unreadNotifications: number
}

export interface GovernanceInboxItem {
  type: 'REVIEW' | 'PROMOTION' | 'REPORT' | string
  id: number
  title: string
  subtitle?: string
  timestamp?: string
  namespace?: string
  skillSlug?: string
}

export interface GovernanceActivityItem {
  id: number
  action: string
  actorUserId?: string
  actorDisplayName?: string
  targetType?: string
  targetId?: string
  details?: string
  timestamp?: string
}

export interface GovernanceNotification {
  id?: number
  category: string
  entityType: string
  entityId: number
  title: string
  bodyJson?: string
  status: 'UNREAD' | 'READ' | string
  createdAt?: string
  readAt?: string
}

export interface AdminUser {
  userId: string
  username: string
  email?: string
  platformRoles: string[]
  status: string
  createdAt: string
}

export interface AuditLogItem {
  id: string
  userId?: string
  username?: string
  action: string
  details?: string
  requestId?: string
  resourceType?: string
  resourceId?: string
  timestamp: string
  ipAddress?: string
}

// Notification types
export interface NotificationItem {
  id: number
  category: 'PUBLISH' | 'REVIEW' | 'PROMOTION' | 'REPORT'
  eventType: string
  title: string
  bodyJson?: string
  entityType?: string
  entityId?: number
  targetType?: string
  targetId?: number
  targetRoute?: string
  status: 'UNREAD' | 'READ'
  createdAt: string
  readAt?: string
}

export interface NotificationPreferenceItem {
  category: string
  channel: string
  enabled: boolean
}

export interface NotificationUnreadCount {
  count: number
}
