import { AxiosInstance } from 'axios'
import {
  AppVersion,
  CreateVersionInput,
  UpdateVersionInput,
  UploadVersionInput,
  VersionListFilter,
  IVersionRepository,
  ParsedPackageInfo,
  Platform,
} from '@/domain'
import { apiClient } from '../http/api-client'

export class VersionRepositoryImpl implements IVersionRepository {
  private client: AxiosInstance

  constructor(client?: AxiosInstance) {
    this.client = client || apiClient
  }

  async list(filter?: VersionListFilter): Promise<AppVersion[]> {
    const params = new URLSearchParams()
    if (filter?.platform) {
      params.append('platform', filter.platform)
    }
    if (filter?.includeDisabled) {
      params.append('includeDisabled', 'true')
    }

    const response = await this.client.get<AppVersion[]>(
      `/api/v1/versions?${params.toString()}`
    )
    return response.data
  }

  async getById(id: string): Promise<AppVersion> {
    const response = await this.client.get<AppVersion>(`/api/v1/versions/${id}`)
    return response.data
  }

  async create(input: CreateVersionInput): Promise<AppVersion> {
    const response = await this.client.post<AppVersion>('/api/v1/versions', input)
    return response.data
  }

  async update(id: string, input: UpdateVersionInput): Promise<AppVersion> {
    const response = await this.client.put<AppVersion>(
      `/api/v1/versions/${id}`,
      input
    )
    return response.data
  }

  async delete(id: string): Promise<void> {
    await this.client.delete(`/api/v1/versions/${id}`)
  }

  async toggle(id: string, isEnabled: boolean): Promise<void> {
    await this.client.patch(`/api/v1/versions/${id}/toggle`, { isEnabled })
  }

  async upload(input: UploadVersionInput): Promise<AppVersion> {
    const formData = new FormData()
    formData.append('file', input.file)
    // Backend expects uppercase platform (ANDROID, IOS)
    formData.append('platform', input.platform.toUpperCase())
    formData.append('versionName', input.versionName)
    formData.append('buildNumber', input.buildNumber)
    formData.append('isForceUpdate', String(input.isForceUpdate ?? false))

    if (input.changelog) {
      formData.append('changelog', input.changelog)
    }
    if (input.minOsVersion) {
      formData.append('minOsVersion', input.minOsVersion)
    }
    if (input.releaseDate) {
      formData.append('releaseDate', input.releaseDate)
    }

    const response = await this.client.post<AppVersion>(
      '/api/v1/versions/upload',
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        timeout: 300000, // 5 minutes for large file uploads
      }
    )
    return response.data
  }

  async parsePackage(file: File, platform: Platform): Promise<ParsedPackageInfo> {
    const formData = new FormData()
    formData.append('file', file)
    // Backend expects uppercase platform (ANDROID, IOS)
    formData.append('platform', platform.toUpperCase())

    const response = await this.client.post<ParsedPackageInfo>(
      '/api/v1/versions/parse',
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        timeout: 120000, // 2 minutes for parsing
      }
    )
    return response.data
  }
}

export const versionRepository = new VersionRepositoryImpl()
