package com.prodhack.moscow2025.data.repImplementations

import android.util.Log
import com.prodhack.moscow2025.data.base.BaseRepository
import com.prodhack.moscow2025.data.data_providers.api.ApiKtorClient
import com.prodhack.moscow2025.data.data_providers.localInfo.AuthorizationDataStore
import com.prodhack.moscow2025.data.dto.TokenResponse
import com.prodhack.moscow2025.data.dto.mapToData
import com.prodhack.moscow2025.domain.interfaces.AuthRepository
import com.prodhack.moscow2025.domain.models.LoginData
import com.prodhack.moscow2025.domain.models.RegisterData
import io.ktor.client.request.setBody
import io.ktor.client.request.url
import io.ktor.http.ContentType
import io.ktor.http.HttpMethod
import io.ktor.http.contentType
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import org.koin.core.annotation.Single

@Single
class AuthRepositoryImpl(
	ktorClient: ApiKtorClient,
	private val authorizationDataStore: AuthorizationDataStore
) : AuthRepository, BaseRepository() {

	override val defaultKtorClient = ktorClient.authClient

	override fun fetchLoginState(): Flow<Boolean> =
		authorizationDataStore.token.map { it.isNotBlank() }

	override suspend fun signUpRequest(request: RegisterData): Result<String> =
		networkRequest<TokenResponse> {
			url {
				method = HttpMethod.Post
				url("/auth/sign_up/email")
				setBody(request.mapToData())
				contentType(ContentType.Application.Json)
			}
		}.map {
			authorizationDataStore.saveToken(it.token)
			"Success"
		}

	override suspend fun signInRequest(request: LoginData): Result<String> =
		networkRequest<TokenResponse> {
			url {
				method = HttpMethod.Post
				url("/auth/sign_in/email")
				setBody(request.mapToData())
				contentType(ContentType.Application.Json)
			}
		}.map {
			authorizationDataStore.saveToken(it.token)
			"Success"
		}

	override suspend fun clearLoginData() {
		authorizationDataStore.clearToken()
	}
}