// data/model/ApiCallRecord.kt
package com.example.initiateaphonecallapp.data.model

import com.example.initiateaphonecallapp.enums.CallStatus
import com.google.gson.annotations.SerializedName
import java.text.SimpleDateFormat
import java.time.LocalDateTime
import java.util.Calendar
import java.util.Date
import java.util.Locale

/**
 * 后端返回的通话记录数据结构
 */
data class ApiCallRecord(
    @SerializedName("id")
    val id: Long,

    @SerializedName("userId")
    val userId: Long,

    @SerializedName("phone")
    val phone: String,

    @SerializedName("duration")
    val duration: Int, // 单位：秒

    @SerializedName("status")
    val status: Boolean, // true表示成功，false表示失败

    @SerializedName("fileUrl")
    val fileUrl: String?,

    @SerializedName("createTime")
    val createTime: String // ISO 8601格式：2025-11-18T09:51:41
)

/**
 * 后端返回的包装结构
 */
data class ApiResponse<T>(
    @SerializedName("msg")
    val message: String,

    @SerializedName("code")
    val code: Int,

    @SerializedName("data")
    val data: T
)

data class CallRecordRequest(
    val startTime: String? = null,
    val endTime: String? = null
)

// 扩展函数：将ApiCallRecord转换为前端的CallRecord
fun ApiCallRecord.toCallRecord(): CallRecord {
    val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault())
    val startTime = dateFormat.parse(createTime) ?: Date()

    // 计算结束时间（开始时间 + 持续时间）
    val endTime = if (duration > 0) {
        Calendar.getInstance().apply {
            time = startTime
            add(Calendar.SECOND, duration)
        }.time
    } else {
        null
    }

    return CallRecord(
        id = id.toString(),
        phoneNumber = phone,
        startTime = startTime,
        endTime = endTime,
        duration = duration.toLong(),
        status = if (status) CallStatus.COMPLETED else CallStatus.FAILED,
        audioFileName = extractFileNameFromUrl(fileUrl),
        audioFileUri = fileUrl,
        uploaded = fileUrl != null && fileUrl.isNotEmpty(),
        uploadTime = if (fileUrl != null && fileUrl.isNotEmpty()) startTime else null
    )
}

// 辅助函数：从URL中提取文件名
private fun extractFileNameFromUrl(url: String?): String? {
    return url?.substringAfterLast('/')?.substringBefore('?')
}

// 扩展函数：批量转换
fun List<ApiCallRecord>.toCallRecords(): List<CallRecord> {
    return this.map { it.toCallRecord() }
}