//
//  Sound.swift
//  AudioPlaybackKit
//
//  Created by Matt Bruce on 9/8/25.
//

import Foundation

/// Sound data model for audio files
public struct Sound: Identifiable, Hashable, Codable {
    public let id: String
    public let name: String
    public let fileName: String
    public let category: String
    public let description: String
    public let bundleName: String? // Optional bundle name for organization
    public let isDefault: Bool? // Optional - used for alarm sounds to mark default
    
    // MARK: - Initialization
    public init(id: String? = nil, name: String, fileName: String, category: String, description: String, bundleName: String? = nil, isDefault: Bool? = nil) {
        self.id = id ?? UUID().uuidString // Use provided id or generate GUID
        self.name = name
        self.fileName = fileName
        self.category = category
        self.description = description
        self.bundleName = bundleName
        self.isDefault = isDefault
    }
    
    // MARK: - Codable Custom Implementation
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        // Generate a new GUID for each sound loaded from JSON
        self.id = UUID().uuidString
        
        self.name = try container.decode(String.self, forKey: .name)
        self.fileName = try container.decode(String.self, forKey: .fileName)
        self.category = try container.decode(String.self, forKey: .category)
        self.description = try container.decode(String.self, forKey: .description)
        self.bundleName = try container.decodeIfPresent(String.self, forKey: .bundleName)
        self.isDefault = try container.decodeIfPresent(Bool.self, forKey: .isDefault)
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        
        try container.encode(id, forKey: .id)
        try container.encode(name, forKey: .name)
        try container.encode(fileName, forKey: .fileName)
        try container.encode(category, forKey: .category)
        try container.encode(description, forKey: .description)
        try container.encodeIfPresent(bundleName, forKey: .bundleName)
        try container.encodeIfPresent(isDefault, forKey: .isDefault)
    }
    
    private enum CodingKeys: String, CodingKey {
        case id, name, fileName, category, description, bundleName, isDefault
    }
    
    // MARK: - Hashable
    public func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
    
}
