import Foundation
import SwiftData

@Model
final class LibraryBook {
    @Attribute(.unique) var localId: UUID
    var title: String
    var authorsString: String
    var coverUrlString: String?
    var isbn10: String?
    var isbn13: String?
    var publishedYear: Int?
    var categoriesString: String
    var summary: String?
    var dateAdded: Date
    var language: String?
    var sourceLocale: String?
    var remotePayloadJson: String?
    // Optional tutulur ki eski store'lar migration sırasında kırılmasın.
    var statusRaw: String?
    var readingProgress: Double?

    init(
        localId: UUID = UUID(),
        title: String,
        authorsString: String,
        coverUrlString: String? = nil,
        isbn10: String? = nil,
        isbn13: String? = nil,
        publishedYear: Int? = nil,
        categoriesString: String = "",
        summary: String? = nil,
        dateAdded: Date = .now,
        language: String? = nil,
        sourceLocale: String? = nil,
        remotePayloadJson: String? = nil,
        statusRaw: String = ReadingStatus.wantToRead.rawValue,
        readingProgress: Double = 0
    ) {
        self.localId = localId
        self.title = title
        self.authorsString = authorsString
        self.coverUrlString = coverUrlString
        self.isbn10 = isbn10
        self.isbn13 = isbn13
        self.publishedYear = publishedYear
        self.categoriesString = categoriesString
        self.summary = summary
        self.dateAdded = dateAdded
        self.language = language
        self.sourceLocale = sourceLocale
        self.remotePayloadJson = remotePayloadJson
        self.statusRaw = statusRaw
        self.readingProgress = min(max(readingProgress, 0), 1)
    }

    var authors: [String] {
        authorsString
            .split(separator: ",")
            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
            .filter { !$0.isEmpty }
    }

    var categories: [String] {
        categoriesString
            .split(separator: ",")
            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
            .filter { !$0.isEmpty }
    }

    var status: ReadingStatus {
        get { ReadingStatus(rawValue: statusRaw ?? "") ?? .wantToRead }
        set { statusRaw = newValue.rawValue }
    }

    var readingProgressValue: Double {
        get { min(max(readingProgress ?? 0, 0), 1) }
        set { readingProgress = min(max(newValue, 0), 1) }
    }
}
