// // SavedProfilesStore.swift // App for Indeed // import Foundation struct PersonalInformation: Codable, Equatable { var fullName: String var email: String var phone: String var jobTitle: String var address: String static let empty = PersonalInformation(fullName: "", email: "", phone: "", jobTitle: "", address: "") } struct WorkExperiencePayload: Codable, Equatable { var jobTitle: String var company: String var duration: String var description: String static let empty = WorkExperiencePayload(jobTitle: "", company: "", duration: "", description: "") } struct EducationPayload: Codable, Equatable { var degree: String var institution: String var year: String static let empty = EducationPayload(degree: "", institution: "", year: "") } struct SavedProfile: Codable, Equatable, Identifiable { var id: UUID var profileDisplayName: String var personal: PersonalInformation var careerSummary: String var workExperiences: [WorkExperiencePayload] var educations: [EducationPayload] var certificates: String var interests: String var languages: String var referral: String } enum SavedProfilesStore { private static let profilesKey = "com.appforindeed.savedProfiles.v1" private static let legacyPersonalKey = "com.appforindeed.personalInformation.v1" static func loadAll() -> [SavedProfile] { migrateLegacyPersonalInformationIfNeeded() guard let data = UserDefaults.standard.data(forKey: profilesKey) else { return [] } do { return try JSONDecoder().decode([SavedProfile].self, from: data) } catch { return [] } } static func saveAll(_ profiles: [SavedProfile]) { do { let data = try JSONEncoder().encode(profiles) UserDefaults.standard.set(data, forKey: profilesKey) } catch { // Best-effort persistence. } } static func upsert(_ profile: SavedProfile) { var all = loadAll() if let i = all.firstIndex(where: { $0.id == profile.id }) { all[i] = profile } else { all.append(profile) } saveAll(all) } static func delete(id: UUID) { var all = loadAll() all.removeAll { $0.id == id } saveAll(all) } static func profile(id: UUID) -> SavedProfile? { loadAll().first { $0.id == id } } /// Imports the older single `PersonalInformation` blob into the first saved profile when the new store has never been written. private static func migrateLegacyPersonalInformationIfNeeded() { guard UserDefaults.standard.object(forKey: profilesKey) == nil else { return } guard let data = UserDefaults.standard.data(forKey: legacyPersonalKey) else { return } guard let personal = try? JSONDecoder().decode(PersonalInformation.self, from: data) else { UserDefaults.standard.removeObject(forKey: legacyPersonalKey) return } let imported = SavedProfile( id: UUID(), profileDisplayName: "My profile", personal: personal, careerSummary: "", workExperiences: [.empty], educations: [.empty], certificates: "", interests: "", languages: "", referral: "" ) saveAll([imported]) UserDefaults.standard.removeObject(forKey: legacyPersonalKey) } }