import APIClient
import ComposableArchitecture
import UserConfigClient

@Reducer
public struct RemixabilityReducer {
    public init() {}

    public struct State: Equatable {
        public init() {}
    }

    public enum Action {
        case optIntoRemixability(Bool)
    }

    @Dependency(\.apiClientV2) private var api
    @Dependency(\.userConfigClient) private var userConfig

    public var body: some ReducerOf<Self> {
        Reduce { _, action in
            switch action {
            case let .optIntoRemixability(optedIn):
                return .run { _ in
                    let response = await Result {
                        try await api.setAllRemixPermissions(optedIn)
                    }

                    switch response {
                    case .success:
                        log.debug("Successfully set remix permissions to \(String(optedIn))")
                        await userConfig.update(UserConfigSchema(hasSetRemixPerm: true))

                    case let .failure(error):
                        log.telemetry.error(error, message: "Error setting remix permissions.")
                    }
                }
            }
        }
    }
}
