import Foundation

struct ThreadSummary: Codable, Identifiable {
	let threadId: String
	let subject: String
	let authors: String
	let totalMessages: Int
	let tags: String
	let timestamp: Int
	let accountId: String

	var id: String { threadId }

	var tagList: [String] {
		tags.split(separator: ",").map(String.init)
	}

	var isUnread: Bool {
		tagList.contains("unread")
	}

	var date: Date {
		Date(timeIntervalSince1970: TimeInterval(timestamp))
	}
}

struct EmailMessage: Codable, Identifiable {
	let messageId: String
	let threadId: String
	let fromHeader: String
	let toHeader: String
	let subject: String
	let date: String
	let inReplyTo: String
	let body: String
	let tags: String
	let timestamp: Int
	let accountId: String

	var id: String { messageId }

	var senderName: String {
		if let range = fromHeader.range(of: " <") {
			return String(fromHeader[..<range.lowerBound])
		}
		return fromHeader
	}
}

struct ThreadListResponse: Codable {
	let threads: [ThreadSummary]
}

struct MessageListResponse: Codable {
	let messages: [EmailMessage]
}

@Observable
final class APIClient {
	private let baseURL: URL

	init(baseURL: URL) {
		self.baseURL = baseURL
	}

	func fetchThreads(accountId: String) async throws -> [ThreadSummary] {
		var components = URLComponents(
			url: baseURL.appendingPathComponent("api/threads"),
			resolvingAgainstBaseURL: false
		)!
		components.queryItems = [URLQueryItem(name: "accountId", value: accountId)]

		let (data, _) = try await URLSession.shared.data(from: components.url!)
		return try JSONDecoder().decode(ThreadListResponse.self, from: data).threads
	}

	func fetchMessages(threadId: String) async throws -> [EmailMessage] {
		let url = baseURL.appendingPathComponent("api/threads/\(threadId)/messages")
		let (data, _) = try await URLSession.shared.data(from: url)
		return try JSONDecoder().decode(MessageListResponse.self, from: data).messages
	}
}
