import SwiftData
import Foundation

@Model
public final class Conversation {
    public var id: String = ""
    public var scenario: String = ""
    public var level: String = ""
    public var messages: String = "[]"
    public var createdDate: Date = Date()

    public init(scenario: String, level: String) {
        self.id = UUID().uuidString
        self.scenario = scenario
        self.level = level
        self.messages = "[]"
        self.createdDate = Date()
    }
}

public struct ChatMessage: Codable, Identifiable, Hashable {
    public var id: String
    public let role: String    // "assistant" or "user"
    public let content: String
    public let correction: String?

    public init(role: String, content: String, correction: String? = nil) {
        self.id = UUID().uuidString
        self.role = role
        self.content = content
        self.correction = correction
    }
}

extension Conversation {
    public var decodedMessages: [ChatMessage] {
        guard let data = messages.data(using: .utf8) else { return [] }
        return (try? JSONDecoder().decode([ChatMessage].self, from: data)) ?? []
    }

    public func appendMessage(_ message: ChatMessage) {
        var msgs = decodedMessages
        msgs.append(message)
        if let data = try? JSONEncoder().encode(msgs), let str = String(data: data, encoding: .utf8) {
            messages = str
        }
    }
}
