package com.aiosman.ravenow.data

import com.aiosman.ravenow.data.api.ApiClient
import com.aiosman.ravenow.data.api.CaptchaRequestBody
import com.aiosman.ravenow.data.api.CaptchaResponseBody
import com.aiosman.ravenow.data.api.CheckLoginCaptchaRequestBody
import com.aiosman.ravenow.data.api.GenerateLoginCaptchaRequestBody


interface CaptchaService {
    suspend fun generateCaptcha(source: String): CaptchaResponseBody
    suspend fun checkLoginCaptcha(username: String): Boolean
    suspend fun generateLoginCaptcha(username: String): CaptchaResponseBody
}

class CaptchaServiceImpl : CaptchaService {
    override suspend fun generateCaptcha(source: String): CaptchaResponseBody {
        val resp = ApiClient.api.generateCaptcha(
            CaptchaRequestBody(source)
        )
        val data = resp.body() ?: throw Exception("Failed to generate captcha")
        return data.data.copy(
            masterBase64 = data.data.masterBase64.replace("data:image/jpeg;base64,", ""),
            thumbBase64 = data.data.thumbBase64.replace("data:image/png;base64,", "")
        )
    }

    override suspend fun checkLoginCaptcha(username: String): Boolean {
        val resp = ApiClient.api.checkLoginCaptcha(
            CheckLoginCaptchaRequestBody(username)
        )
        return resp.body()?.data ?: true
    }

    override suspend fun generateLoginCaptcha(username: String): CaptchaResponseBody {
        val resp = ApiClient.api.generateLoginCaptcha(
            GenerateLoginCaptchaRequestBody(username)
        )
        val data = resp.body() ?: throw Exception("Failed to generate captcha")
        return data.data.copy(
            masterBase64 = data.data.masterBase64.replace("data:image/jpeg;base64,", ""),
            thumbBase64 = data.data.thumbBase64.replace("data:image/png;base64,", "")
        )
    }
}