import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const apiPath = path.join(__dirname, '../src/services/api.ts')
let content = fs.readFileSync(apiPath, 'utf8')

// Remove errorData blocks after authFetch/fetch
content = content.replace(
  /\s*if \(!response\.ok\) \{\s*const errorData = await response\.json\(\)\s*throw new Error\(errorData\.message \|\| '[^']*'\)\s*\}/g,
  ''
)

// Remove simple throw patterns
content = content.replace(/\s*if \(!response\.ok\) throw new Error\('[^']*'\)/g, '')

// return data.result -> parseApiResponse
content = content.replace(
  /const data = await response\.json\(\)\s*return data\.result/g,
  'return await parseApiResponse(response)'
)

// return (data.result?.list || []) patterns
content = content.replace(
  /const data = await response\.json\(\)\s*\/\/[^\n]*\n\s*return \(data\.result\?\.([^)]+)\)/g,
  'const data = await parseApiResponse<any>(response)\n    return (data?.$1)'
)

content = content.replace(
  /const data = await response\.json\(\)\s*return \(data\.result\?\.([^)]+)\)/g,
  'const data = await parseApiResponse<any>(response)\n    return (data?.$1)'
)

// return data.result || [] 
content = content.replace(
  /const data = await response\.json\(\)\s*return data\.result \|\| \[\]/g,
  'return (await parseApiResponse<any[]>(response)) || []'
)

// const result = data.result as X patterns - keep data line, fix next lines
content = content.replace(
  /const data = await response\.json\(\)\s*const result = data\.result as/g,
  'const result = await parseApiResponse'
)

// login block
content = content.replace(
  /export const login = async \(credentials: LoginRequest\): Promise<LoginResponse> => \{[\s\S]*?\n\}/,
  `export const login = async (credentials: LoginRequest): Promise<LoginResponse> => {
  try {
    const response = await fetch(\`\${API_BASE}/admin/login\`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(credentials),
    })
    const result = await parseApiResponse<{ token: string; user: User; expire: number }>(response, {
      skipSessionExpired: true,
    })
    return {
      token: result.token,
      user: result.user,
      expire: result.expire,
    }
  } catch (error) {
    console.error('Login error:', error)
    throw error
  }
}`
)

// void returns that only had authFetch + ok check - add parseApiResponse
content = content.replace(
  /(const response = await authFetch\([^)]+\)[\s\S]*?\))\s*\n(\s*\} catch)/g,
  (match, fetchPart, catchPart) => {
    if (match.includes('parseApiResponse') || match.includes('return await')) {
      return match
    }
    if (match.includes('method:')) {
      return `${fetchPart}\n    await parseApiResponse(response)\n${catchPart}`
    }
    return match
  }
)

fs.writeFileSync(apiPath, content)
console.log('Migration complete')
